Search code examples
c#xunitfixturesxunit.net

How to share one fixture among all test classes?


I want to share DBfixture in all tests. This is the collection created for this purpose:

[CollectionDefinition("db")]
public class TestColDefinition : IClassFixture<DBfixture> {  }

I have a base class from which i derive my test classes:

public class TestBase
{
    protected readonly ITestOutputHelper testOutputHelper;
    protected DBfixture dbf;

    public TestBase(ITestOutputHelper testOutputHelper, DBfixture dbf)
    {
        this.testOutputHelper = testOutputHelper;
        this.dbf = dbf;
    }
}

[Collection("db")]
public class TestClass1 :  TestBase
{
    public TestClass1(ITestOutputHelper testOutputHelper, DBfixture dbf) : base(testOutputHelper, dbf) { }

    [Fact]
    public void fact(){}
}

[Collection("db")]
public class TestClass2 :  TestBase
{
    public TestClass2(ITestOutputHelper testOutputHelper, DBfixture dbf) : base(testOutputHelper, dbf) { }

    [Fact]
    public void fact(){}
}

But when I run tests two DBfixture objects are created (one for each test class). Without collection four objects are created. How do I setup this so that one object is shared among all test classes?


Solution

  • You can use the collection fixture and add every test under that collection to achieve what you mentioned above. But if you use a single collection fixture then your entire test will run in serial unless you explicitly disable it in Xunitrunner config.

    One of the point from Xunit Docs: Test collections also influence the way xUnit.net runs tests when running them in parallel.

    For more details please read: https://xunit.net/docs/shared-context

    Alternative can be, use a static class to store the DB context which you can assign while starting the test and use that across the test life cycle.