Search code examples
c#.netspecflow

Specflow API Testing with Dynamic Values


When I have a Specflow definition file like the below

Given these products exist
    | Sku   | Name             | Price |
    | BOOK1 | Atlas Shrugged   | 25.04 |
    | BOOK2 | The Fountainhead | 20.15 |

Which maps to the below product class

public class Product
{
    public string Sku { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

And the associated Given is

[Given(@"Given these products exist")]
public void GivenTheseProductsExist(Table table)
{
    var products = table.CreateSet<Product>();
    // ...
}

How can I define dynamic SKU values that change with every execution in the above example?


Solution

  • If the SKU is irrelevant to a particular scenario, simply omit that column from the data table. The SKU will be null in C#. Your step definition can test for null so it auto-generates a SKU.

    Changes to your step:

    Given these products exist
        | Name             | Price |
        | Atlas Shrugged   | 25.04 |
        | The Fountainhead | 20.15 |
    

    Your step definition:

    [Given(@"Given these products exist")]
    public void GivenTheseProductsExist(Table table)
    {
        var products = table.CreateSet<Product>();
    
        foreach (var product in products)
        {
            if (product.Sku == null)
            {
                product.Sku = AutoGenerateSku();
            }
    
            // save product to database or web service
        }
    }
    

    This gives you some flexibility in writing your scenarios, which may or may not be desirable.

    You can still include an SKU column in your step, but leave the value empty:

    Given these products exist
        | Sku | Name             | Price |
        |     | Atlas Shrugged   | 25.04 |
        |     | The Fountainhead | 20.15 |
    

    The SKU would come across in C# as an empty string: "". This would fail the null check and attempt to create the product with an empty string for an SKU. If this behavior is not desirable, use string.IsNullOrEmpty(product.Sku) before auto-generating the SKU in your step definition:

    if (string.IsNullOrEmpty(product.Sku))
    {
        product.Sku = AutoGenerateSku();
    }