In Specflow can I run one test as a step of another?

前端 未结 4 902
庸人自扰
庸人自扰 2020-12-06 05:25

TL;DR; How can I create a specflow test that calls another test as its first step?

Given I already have one specflow test
And I want to run          


        
4条回答
  •  星月不相逢
    2020-12-06 06:23

    You don't need to run actual steps to create a sales order. Just implement a step definition that does this for you as a one-liner.

    First, the fictional SalesOrder class:

    public class SalesOrder
    {
        public double Amount { get; set; }
        public string Description { get; set; }
    }
    

    Then the step definitions

    using TechTalk.SpecFlow;
    using TechTalk.SpecFlow.Assist;
    
    [Binding]
    public class SalesOrderSteps
    {
        [Given("I have already created a Sales Order")]
        public void GivenIHaveAlreadyCreatedASalesOrder()
        {
            var order = new SalesOrder()
            {
                // .. set default properties
            };
    
            // Save to scenario context so subsequent steps can access it
            ScenarioContext.Current.Set(order);
    
            using (var db = new DatabaseContext())
            {
                db.SalesOrders.Add(order);
                db.SaveChanges();
            }
        }
    
        [Given("I have already created a Sales Order with the following attributes:")]
        public void GivenIHaveAlreadyCreatedASalesOrderWithTheFollowingAttributes(Table table)
        {
            var order = table.CreateInstance();
    
            // Save to scenario context so subsequent steps can access it
            ScenarioContext.Current.Set(order);
    
            using (var db = new DatabaseContext())
            {
                db.SalesOrders.Add(order);
                db.SaveChanges();
            }
        }
    }
    

    Now you can create Sales orders as a one-liner and optionally include some custom attributes:

    Scenario: Something
        Given I have already created a Sales Order
    
    Scenario: Something else
        Given I have already created a Sales Order with the following attributes:
            | Field       | Value             |
            | Amount      | 25.99             |
            | Description | Just a test order |
    

    If you need to access that SalesOrder object in other step definitions without querying for it in the database, use ScenarioContext.Current.Get() to retrieve that object from the scenario context.

提交回复
热议问题