简体   繁体   中英

Have NUNIT run tests in parallel

I have a DBContext within my tests for EF Core

Each test is responsible for setting up this context

How can I get NUnit to be able to run my tests in parallel with each test having its own dbContext where the dbcontext is a field of the class

It appears as though each run is reusing the fields in the test class, I want a brand new instance created for each test?

Following the answer below I added FixtureLifeCycleAttribute.InstancePerTest to the top of my test class

    protected virtual DbContext GetDbContext()
    {

        if (_dbContext == null)
        {
            var testName = TestContext.CurrentContext.Test.MethodName + "_" + Guid.NewGuid().ToString();
            Debug.WriteLine($"Creating context for {testName}");
            

            // Create a fresh service provider, and therefore a fresh 
            // InMemory database instance.
            var serviceProvider = new ServiceCollection()
                .AddEntityFrameworkInMemoryDatabase()
                .BuildServiceProvider();

            // Create a new options instance telling the context to use an
            // InMemory database and the new service provider.
            var builder = new DbContextOptionsBuilder<MyDbContext>();
            builder.UseInMemoryDatabase(testName).UseInternalServiceProvider(serviceProvider);

            var options = builder.Options;
            var result = new MyDbContext(options);

            if (ShareContext == false)
            {
                return result;
            }

            _dbContext = result;
        }

        return _dbContext;
    }

I use this

protected MyDbContext DbContext => (MyDbContext)GetDbContext();

So in my tests I add to DbContext.MyTable

If I have 2 separate tests that add the same record to DbContext.MyTable I would not expect this to fail but it does

Paul

In version 3.13, Nunit has added a support for instance per test case by simply choosing LifeCycle.InstancePerTestCase value when placing the FixtureLifeCycleAttribute on top of the test class. See docs here https://docs.nunit.org/articles/nunit/writing-tests/attributes/fixturelifecycle.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM