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

大憨熊 提交于 2019-12-03 12:34:14

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

Well, this answer is a bazillion years late based on the original problem date but...

I discovered if the test agent (QTAgent32.exe) crashes or dies before the complete sequence finishes, then AssemblyInitialize (and maybe ClassInitialize and TestInitialize) would be called again. For example, put this in your [AssemblyCleanup] function and you'll see the behavior occur:

Process p = AutotestShared.RunProcess("cmd", "/c taskkill /t /f /im QTAgent32.exe", true);
p.WaitForExit();

So the moral of this story is: Check your cleanup functions to see if there are any crashes / corruption. Failures during cleanup don't show in the test report because the pass/fail assertions are already complete. But the problems it causes may show up in other ways.

In my case, it was a misbehavior of QTAgent32.exe process that was causing [AssemblyInitialize] to be executed twice. Restarting the host machine where my code was built and executed solved the issue for me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!