简体   繁体   English

让 NUNIT 并行运行测试

[英]Have NUNIT run tests in parallel

I have a DBContext within my tests for EF Core我的 EF Core 测试中有一个 DBContext

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如何让 NUnit 能够与每个具有自己的 dbContext 的测试并行运行我的测试,其中 dbcontext 是 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?似乎每次运行都在重用测试 class 中的字段,我想要为每个测试创建一个全新的实例?

Following the answer below I added FixtureLifeCycleAttribute.InstancePerTest to the top of my test class按照下面的答案,我将 FixtureLifeCycleAttribute.InstancePerTest 添加到我的测试 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();受保护的 MyDbContext DbContext => (MyDbContext)GetDbContext();

So in my tests I add to DbContext.MyTable所以在我的测试中我添加到 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如果我有 2 个单独的测试将相同的记录添加到 DbContext.MyTable 我不会期望这会失败,但确实如此

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.在 3.13 版中,Nunit 添加了对每个测试用例实例的支持,只需在将 FixtureLifeCycleAttribute 放在测试 class 顶部时选择 LifeCycle.InstancePerTestCase 值即可。 See docs here https://docs.nunit.org/articles/nunit/writing-tests/attributes/fixturelifecycle.html请参阅此处的文档https://docs.nunit.org/articles/nunit/writing-tests/attributes/fixturelifecycle.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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