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

2.5k Views Asked by At

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. enter image description here

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?

1

There are 1 best solutions below

4
On BEST ANSWER

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