79E09796
79E09796

Reputation: 2230

Dynamic context injection in Specflow

Using Specflow's basic dependency injection, it is possible to inject a dynamic context object as below.

This saves having to use the dictionary which I find clunky, are there drawbacks to this approach?

public class TestClass
{
    private readonly dynamic context;

    public TestClass(ExpandoObject context)
    {
        this.context = context;
    }

    [Given(@"I have a file")]
    public void GivenIHaveAFile()
    {
        context.FilePath = @".\Folder\File";
    }

    [When(@"I use the file")]
    public void GivenIHaveAFile()
    {
        var fileContents = File.ReadAllText(context.FilePath);
    }
}

Upvotes: 1

Views: 440

Answers (1)

Sam Holder
Sam Holder

Reputation: 32936

The drawbacks are only those that you get with using dynamic objects in general. You'll get no intellisense and won't be able to add any behaviour to your object.

Personally I prefer to use specific classes to handle passing state between steps as these objects can then be assigned behaviour as well as holding data, but YMMV.

In place of the generic dictionary though this seems reasonable, as it at least avoids the casting.

Upvotes: 3

Related Questions