簡體   English   中英

MSTest V2 按順序執行單元測試 -> [DoNotParallelize]

[英]MSTest V2 Execute UnitTests sequentially -> [DoNotParallelize]

我對按順序運行 UnitTests 有疑問。 不幸的是,在這種情況下,不能選擇並行運行它們或模擬數據庫。 該項目是在 .NET 核心 3.1 中編寫的,單元測試需要在單元測試運行前后執行數據庫操作。

在閱讀https://www.meziantou.net/mstest-v2-execute-tests-in-parallel.htm和許多其他關於順序單元測試的文章后,我想出了這個(簡化):

基類:

namespace XY.Test
{
    [TestClass]
    public class BaseTest: TimerModel
    {
        private static readonly DbCreator Creator = new DbCreator();
        public static readonly DbConnectionManager ConnectionManager = new DbConnectionManager();

        [TestInitialize]
        public void BaseTestInitialize()
        {
            CreateTestData();
        }

        [TestCleanup]
        public void BaseTestCleanup()
        {
            RemoveTestData();
        }

        public void CreateTestData()
        {
            RemoveTestData();
            Creator.ExecuteSqlFromScript(ConnectionManager, @"Resources\CreateTestData.sql");
        }

        public void RemoveTestData()
        {
            Creator.ExecuteSqlFromScript(ConnectionManager, @"Resources\EmptyTestDataTables.sql");
        }
    }
}

測試類:

[assembly: Parallelize(Workers = 0, Scope = ExecutionScope.ClassLevel)] //<-- Also tried out Workers = 1 and Scope = ExecutionScope.MethodLevel
namespace XY.Test.Models
{
    [TestClass]
    public class TerminalConfigModelTest: BaseTest
    {
        [TestMethod]
        [DoNotParallelize]
        public void TestMethod1()
        {
            ...
        }

        [TestMethod]
        [DoNotParallelize]
        public void TestMethod2()
        {
            ...
        }
    }
}

出於某種原因,無論我做什么,單元測試都是並行執行的。 為了讓它們按順序執行,我必須改變什么?

當我執行測試 class 中的所有測試時,在運行 TestCleanup 之前,基 class 的 TestInitialize 被調用了兩次。 這會導致 CreateTestData 方法失敗,因為索引會阻止測試數據的雙重插入。

我期望的是:

  • 調用 TestInitialize1
  • 執行 TestMethod1
  • 調用 TestCleanup1
  • 調用 TestInitialize2
  • 執行 TestMethod2
  • 調用 TestCleanup2
  • ...

發生什么了:

  • 調用 TestInitialize1
  • 執行 TestMethod1
  • 在調用 TestCleanup1 之前調用 TestInitialize2
  • TestMethod2 執行失敗

我是否誤解了 [DoNotParallelize] 選項?

並行不是這里的問題,我的測試絕對是順序的,[ClassCleanup] 也把我搞砸了。 這只是不直觀和奇怪,更多信息在這里 我將嘗試使用有序測試並更新答案,我現在能告訴你的最好的事情就是不要使用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM