xUnit IClassFixture constructor being called multiple times
Asked Answered
A

2

9

I am using xUnit for integration testing. and for that, I use a localdb instance for it. With that being said, I would like to initiate DB instance once with some pre-defined data and of course I would that stay true for all test cases. I could write each test cases isolated so they are not running into each other however I would like to only create DB instance once.

I followed xunit constructor runs before each test and the code looks like

//similar to base class
public class DatabaseFixture : IDisposable
{
    public SqlConnection Db { get; private set; }
    public DatabaseFixture()
    {
        InitialDB();
    }
    public InitialDB()
    {
        CreateDBInstance();
        CreateDBSchemas();
        InitDBMetaData();
    }

    public void Dispose()
    {
        // clean up test data from the database
        CleanUpDB();
    }
}

//Class where you want to use shared class instance
public class MyDatabaseTests : IClassFixture<DatabaseFixture>
{
    DatabaseFixture dbFixture;
    public MyDatabaseTests(DatabaseFixture fixture)
    {
        this.dbFixture = fixture;
    }

// write tests, using dbFixture.Db to get access to the SQL Server
}

The problem I am facing is I noticed this DBFixture being called everytime per test case. I thought with iClassFixture it is only called once. which brings problem when test cases run in parallel because it is trying to cleanup db while other test trying to access it and also multiple test cases would try to create the db at the same time which causes error. https://xunit.net/docs/shared-context.html

Can anyone shed light on why it is not working?

Ajax answered 5/5, 2020 at 0:0 Comment(1)
btw I tried to set a breakpoint at my dispose method from fixture class. I have 4 tests and it hit dispose when two of them turning green. of course, rest two would failAjax
E
4

I stumbled across the same problem and it was an issue with visual studio: https://github.com/xunit/xunit/issues/2347#issuecomment-983586580

Right clicking the class file which contains the tests to start the test runner, may lead to this behaviour.

Ethnography answered 26/1, 2022 at 19:26 Comment(2)
It still happens for me even if I run my tests via Test Explorer window.Joniejonina
Nice, works for me. Although the issue was created for VS2019, it still does the same with VS2022 for me.Unknowing
R
1

You need to use Collection Fixtures instead.

https://xunit.net/docs/shared-context#collection-fixture

When to use: when you want to create a single test context and share it among tests in several test classes, and have it cleaned up after all the tests in the test classes have finished.

Rosol answered 10/2, 2021 at 10:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.