繁体   English   中英

让 NUNIT 并行运行测试

[英]Have NUNIT run tests in parallel

我的 EF Core 测试中有一个 DBContext

每个测试负责设置这个上下文

如何让 NUnit 能够与每个具有自己的 dbContext 的测试并行运行我的测试,其中 dbcontext 是 class 的字段

似乎每次运行都在重用测试 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;
    }

我用这个

受保护的 MyDbContext DbContext => (MyDbContext)GetDbContext();

所以在我的测试中我添加到 DbContext.MyTable

如果我有 2 个单独的测试将相同的记录添加到 DbContext.MyTable 我不会期望这会失败,但确实如此

保罗

在 3.13 版中,Nunit 添加了对每个测试用例实例的支持,只需在将 FixtureLifeCycleAttribute 放在测试 class 顶部时选择 LifeCycle.InstancePerTestCase 值即可。 请参阅此处的文档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