Author : HASSAN MD TAREQ

Points to Note

  • Test constructor (setup) and dispose (teardown) will be called per test which is expensive if constructor contains heavy lifting thats why we need shared context ()
  • When using shared context, setup and teardown will be shared (all tests of a class or across many classes)
  • Use IClassFixure<T> for sharing context between tests (all test of a class will share same setup and teardown)
  • Use ICollectionFixture<T> for sharing context across multiple test classes
  • Shared Context between Tests

IClassFixture

FooFixture.cs

public class FooFixture : IDisposable
{
    public Foo State { get; private set; }

    public FooFixture()
    {
        State = new Foo();
    }

    public void Dispose()
    {
        // Cleanup
    }
}

FooTest.cs

public class FooTest : IClassFixture<FooFixture>
{
    private readonly FooFixture _fooFixture;

    public FooTest(FooFixture fooFixture)
    {
        _fooFixture = fooFixture;
    }

    [Fact]
    public void ATest()
    {
        // Assert here
        // use _fooFixture.State to test Foo class
    }
}

ICollectionFixture

FooCollectionFixture.cs (using FooFixture.cs)

[CollectionDefinition("FooFixtureCollection")]
public class GameStateCollection : ICollectionFixture<FooFixture> {}

Using in TestClassOne.cs

[Collection("FooFixtureCollection")]
public class TestClassOne
{
    private readonly GameStateFixture _gameStateFixture;

    public TestClassOne(GameStateFixture gameStateFixture)
    {
        _gameStateFixture = gameStateFixture;
    }

    [Fact]
    public void ATest()
    {
        // Assert here
        // use _fooFixture.State to test Foo class
    }
}

Using in TestClassTwo.cs

[Collection("FooFixtureCollection")]
public class TestClassTwo
{
    private readonly GameStateFixture _gameStateFixture;

    public TestClassTwo(GameStateFixture gameStateFixture)
    {
        _gameStateFixture = gameStateFixture;
    }

    [Fact]
    public void ATest()
    {
        // Assert here
        // use _fooFixture.State to test Foo class
    }
}