mwhelan / Specify

Specify is an opinionated .Net Core testing library that builds on top of BDDfy from TestStack
http://specify-dotnet.readthedocs.org/
MIT License
20 stars 8 forks source link

SUT needs to be reset for Examples #29

Open mwhelan opened 6 years ago

mwhelan commented 6 years ago

Specify currently creates the SUT and container per scenario, but needs to do so per test case when examples are used. This causes an issue when subsequent test cases attempt to set dependencies in the container. An exception is thrown because the SUT has been set. This is expected behaviour for a scenario but needs to be enhanced to handle the situation with test cases.

public class ExampleScenario : ScenarioFor<ConcreteObjectWithOneInterfaceConstructor>
{
    private int _result;
    private IDependency1 _dependency;

    public ExampleScenario()
    {
        Examples = new ExampleTable("Num", "Result")
        {
            {1, 1},
            {2, 2}
        };
    }
    public void GivenTheValue(int num)
    {
        _dependency = new Dependency1 { Value = num };
        Container.Set<IDependency1>(_dependency);
    }
    public void WhenICheckTheDependencyValue()
    {
        _result = SUT.Dependency1.Value;
    }
    public void ThenItShouldBe_(int result)
    {
        _result.ShouldBe(result);
    }
}

Specify resolves each scenario from the IoC container and provides a fresh child container per scenario. The constructor runs once. Then, for each Example test case, the BDDfy methods run (Given When Then etc.). This means each test case is sharing the SUT and container. This will be fixed in the next release of Specify, but a workaround for the moment is to reset the SUT for each Example test case. This can be achieved by adding a Setup method.

public class ExampleScenario : ScenarioFor<ConcreteObjectWithOneInterfaceConstructor>
{
    private int _result;
    private IDependency1 _dependency;

    public ExampleScenario()
    {
        Examples = new ExampleTable("Num", "Result")
        {
            {1, 1},
            {2, 2}
        };
    }
    public void Setup()
    {
        SUT = null;
    }
    public void GivenTheValue(int num)
    {
        _dependency = new Dependency1 { Value = num };
        Container.Set<IDependency1>(_dependency);
    }
    public void WhenICheckTheDependencyValue()
    {
        _result = SUT.Dependency1.Value;
    }
    public void ThenItShouldBe_(int result)
    {
        _result.ShouldBe(result);
    }
}