Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xUnit IClassFixture constructor being called multiple times

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?

like image 756
Yili Li Avatar asked May 01 '26 10:05

Yili Li


1 Answers

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.

like image 185
Alex Avatar answered May 04 '26 10:05

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!