簡體   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