为什么在同一测试项目程序集中两次调用[AssemblyInitialize]和[AssemblyCleanup]?
我认为这些属性的全部目的是每个程序集仅运行一次.我有一个简单的类,如下所示:
I thought the whole purpose of these attributes was to run them only once per assembly. I have a simple class as follows:
[TestClass]
public class AssemblyIntegrationTestSetup
{
public AssemblyIntegrationTestSetup() { }
public TestContext TestContext { get; set; }
[AssemblyInitialize]
public static void SetupIntegrationTests(TestContext context)
{
WindowsServiceService.Instance.StartService("Distributed Transaction Coordinator");
}
[AssemblyCleanup]
public static void TeardownIntegrationTests()
{
WindowsServiceService.Instance.StopService("Distributed Transaction Coordinator");
}
}
但是,当我运行测试套件时,程序集级的Initialize和Cleanup方法执行两次.以下是有关我的环境的详细信息:
However when I run the test suite the assembly-level Initialize and Cleanup methods execute twice. Here are the details about my environemnt:
- 所有测试类都在同一项目/程序集中.
- 我有按名称空间分隔的集成和单元测试.
- 对于集成测试,我使用MSTextExtensions允许回滚数据库事务.
- 我还正在启动/停止MS SQL Server DTC服务,这是回滚功能所必需的.我希望每个测试套件运行一次(并且发现的最佳折衷方法是使用程序集级属性).该代码可以运行,但是执行两次.
- 如果有关系,我在某些测试中还将使用Microsoft Moles Framework.
观察到的行为类似于:
AssemblyInitialize
Class1.TestInitialize
Class1.TestMethod1
Class1.TestCleanup
AssemblyInitalize <-- //This shouldn't be happening right?
Class2.TestInitialize
Class2.TestMethod1
Class2.TestCleanup
Class2.TestInitialize
Class2.TestMethod2
Class2.TestCleanup
Class5.TestInitialize
Class5.TestMethod1
Class5.TestCleanup
Class7.TestInitialize
Class7.TestMethod1
Class7.TestCleanup
//More random bouncing around then...
AssemblyCleanup
AssemblyCleanup <-- //This shouldn't be happening right?
来自MSDN库文章:
重要
此属性不应在 ASP.NET单元测试,即任何测试 [HostType("ASP.NET")]属性. 由于IIS的无状态性质 和ASP.NET,一种用 此属性可能被称为更多 每次测试运行一次.
This attribute should not be used on ASP.NET unit tests, that is, any test with [HostType("ASP.NET")] attribute. Because of the stateless nature of IIS and ASP.NET, a method decorated with this attribute might be called more than once per test run.
您可以在测试运行器中调整一些旋钮.我只是用一个计数器来解决这个问题:
There are few knobs you can tweak in test runner. I would just punt the problem with a counter:
private int InitCount;
[AssemblyInitialize]
public static void SetupIntegrationTests(TestContext context)
{
if (InitCount++ == 0) {
WindowsServiceService.Instance.StartService("Distributed Transaction Coordinator");
}
}
[AssemblyCleanup]
public static void TeardownIntegrationTests()
{
if (--InitCount == 0) {
WindowsServiceService.Instance.StopService("Distributed Transaction Coordinator");
}
}