我认为这些属性的全部目的是每个程序集仅运行一次。我有一个简单的类,如下所示:
[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方法执行两次。以下是有关我的环境的详细信息:
观察到的行为类似于:
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库文章:
Important
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.
您可以在测试运行器中调整一些旋钮。我只是用一个计数器来解决这个问题:
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");
}
}
关于visual-studio-2008 - 为什么在同一测试项目程序集中两次调用[AssemblyInitialize]和[AssemblyCleanup]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4029886/