Why is [AssemblyInitialize] and [AssemblyCleanup] being called twice in same test project assembly?

后端 未结 3 729
不思量自难忘°
不思量自难忘° 2021-02-15 02:08

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 AssemblyIntegr         


        
3条回答
  •  滥情空心
    2021-02-15 03:03

    From the MSDN Library article:

    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.


    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");
          }
    }
    

提交回复
热议问题