简体   繁体   中英

ClassInitialize doesn't execute when trying to run test cases grouped by classes

I have a couple of TestClasses each having few TestMethods.Again I need to create data for each of these TestMethods, all of which is handles in a SuiteBase file which is inherited by each of the TestClasses. I need to create the data once for each TestClass, so that all the TestMethods in that class can use the same data. For this reason I have put the data creation code under ClassInitialize in the SuiteBase file. Structure of SuiteBase:

    public class SuiteBase
{
    [ClassInitialize]
    public void ClassInit()
    {
        //Create the data for the all test cases under one TestClass          
    }

    [TestInitialize]
    public void Init()
    {
        //Starts the app each time for each TestMethod
    }

TestClass structure:

    [TestClass()]
public class ScenarioOne :  SuiteBase
{
    [TestMethod()]
    public void TestCase1()
    {
        //Blah Blah
    }

            [TestMethod()]
    public void TestCase2()
    {
        //Blah Blah
    }

            [TestMethod()]
    public void TestCase3()
    {
        //Blah Blah
    }
}

Now I am trying to run the unit tests(grouped by class) from my test explorer. 在此处输入图片说明

Theoretically,before any of the TestMethods start, the ClassInitialize code in SuiteBase should work first.But I see that the ClassInitialize code is not just run. I put a breakpoint in ClassInitialize and debugged,the code was not executed at all. Is my assumption wrong in the behavior of ClassInitialize or I am doing something fundamentally wrong here?

Unfortunately ClassInitializeAttribute method cant be inherited. Since the ClassInitializeAttribute cannot be inherited, when the ScenarioOne class is initialized the ClassInitialize method from the SuiteBase class cannot be called.

Try to solve it, you will have to define again the ClassInitialize method in ScenarioOne and just call the base method instead of duplicating the code.

[TestClass()]
public class ScenarioOne : SuiteBase
{
    [ClassInitialize]
    public static void ClassInit()
    {
        SuiteBase.ClassInit();
        //Create the data for the all test cases under one TestClass          
    }
    [TestMethod()]
    public void TestCase1()
    {
        //Blah Blah
    }

    [TestMethod()]
    public void TestCase2()
    {
        //Blah Blah
    }

    [TestMethod()]
    public void TestCase3()
    {
        //Blah Blah
    }
}

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM