我有一个关于按顺序运行单元测试的问题。不幸的是,在这种情况下,不能选择并行运行它们或模拟数据库。该项目是用.NET core 3.1编写的,UnitTests需要在Unittest运行之前和之后执行数据库操作。
看完之后https://www.meziantou.net/mstest-v2-execute-tests-in-parallel.htm 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()
{
...
}
}
}
由于某种原因,无论我做什么,单元测试都会并行执行。为了让它们按顺序执行,我必须更改什么?
当我执行测试类中的所有测试时,在运行 TestCleanup 之前,会调用基类的 TestInitialize 两次。这会导致 CreateTestData 方法失败,因为索引会阻止测试数据的双重插入。
我期望什么:
- TestInitialize1 被调用
- 执行测试方法1
- TestCleanup1 被调用
- TestInitialize2 被调用
- 执行测试方法2
- TestCleanup2 被调用
- ...
会发生什么:
- TestInitialize1 被调用
- 执行测试方法1
- 在调用 TestCleanup 1 之前调用 TestInitialize 2
- TestMethod2 执行失败
我是否误解了 [DoNotParallelize] 选项?