ClassInitialize attribute in unit test based class not called

微笑、不失礼 提交于 2019-12-08 14:25:55

问题


I added these method in a TestBase class :

[ClassInitialize]
public static void InitializBeforeAllTests()
{
}

But when I run in Debug an unit test Test1() :

[TestClass]
public class TestMapping : TestBase
{
    [TestMethod]
    public void Test1()
    {
    }

The TestBase.InitializBeforeAllTests() method is never called. Why?


回答1:


When declaring ClassInitialize attribute on a method, the method has to be static, public, void and should take a single parameter of type TestContext.

If you're having also other method with the AssemblyInitialize attribute on the same unit test, the test will run but will skip on all test methods and will go directly to AssemblyCleanup or just quit.

Try the example on ClassInitialize attribute in MSDN.




回答2:


for whatever reason, the unit test framework's UnitTestExecuter only allows one ClassInitialize and one ClassCleanup method to be defined per test class... unlike TestInitialize and TestCleanup methods, which get called in both the derived and base test class...




回答3:


You can setup an assembly initialize method in your base class. Not quite the same as ClassInitialize, but it's a viable option. Source:The Workaround mentioned here.

[TestClass]
public abstract class TestBase
{
    [AssemblyInitializeAttribute]
    public static void Initialize(TestContext context)
    {
        // put your initialize code here
    }
}

You can also add a Cleanup method:

[AssemblyCleanup]
public static void Cleanup()
{
   //clean up stuff here
}



回答4:


The MS link is not working anymore. Anyway, one way to work around this issue is to simply move your initialization code into the constructor of the base class. This will ensure that it gets called from any descendant classes whenever they are instantiated.

[TestClass]
public class TestBase
{
    public TestBase()
    {
        // Initialization Code
    }
}

[TestClass]
public class TestMapping : TestBase
{
    [TestMethod]
    public void Test1()
    {
        // At this point the base constructor should have been called
    }
}



回答5:


In my case, I had the[Ignore] attribute applied (test is ran manually)
This caused [AssemblyInitialize] to never be called

If I removed the [Ignore] attribute [AssemblyInitialize] was called as expected.

Oddly, [AssemblyCleanup] is still called with or without the [Ignore] applied to my test



来源:https://stackoverflow.com/questions/7322154/classinitialize-attribute-in-unit-test-based-class-not-called

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