繁体   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