locked
Skip TestIntialize for few Test Methods RRS feed

  • Question

  • Hi,

    I have a unit tests with few Test Methods. I wanted to run few of these test methods with TestInitialize method and for few I want to skip the Test Initialize method. Please let me know if there is any way to do so. 

    Thanks in Advance.

    Regards,

    Srik

    Tuesday, September 6, 2016 2:22 PM

Answers

  • You can do that if you have 2 test classes - one class has a TestInitialize method and that class contains the tests you want to execute the TestInitialize logic.  The other TestClass does not have a Method with the TestInitialize attribute.  Tests in this class will not call the TestInitialize logic.

    Tim

    • Proposed as answer by lake Xiao Wednesday, September 7, 2016 7:20 AM
    • Marked as answer by SrikEMP Thursday, September 8, 2016 5:25 AM
    Tuesday, September 6, 2016 4:34 PM

All replies

  • You can do that if you have 2 test classes - one class has a TestInitialize method and that class contains the tests you want to execute the TestInitialize logic.  The other TestClass does not have a Method with the TestInitialize attribute.  Tests in this class will not call the TestInitialize logic.

    Tim

    • Proposed as answer by lake Xiao Wednesday, September 7, 2016 7:20 AM
    • Marked as answer by SrikEMP Thursday, September 8, 2016 5:25 AM
    Tuesday, September 6, 2016 4:34 PM
  • Hi Srik,

    Tim's suggestion is recommended.

    TestInitialize method a little bit special. I have tried define a global variable. And in every test method, re-assign the value to the global variable. But the global variable in TestInitialize method will also be initialized as well.

        [TestClass]
        public class UnitTest1
        {
            int a;
            [TestInitialize]
            public void TestInitialize()
            {
                //Console.WriteLine(a);
                if (a == 1)
                {
                    Console.WriteLine("start to test");
                }
                
            }
            [TestMethod]
            public void TestMethod1()
            {
               
                a = 1;
                Assert.AreEqual(1,1);
            }
            [TestMethod]
            public void TestMethod2()
            {
                a = 2;
                Assert.AreEqual(1, 1);
            }
            [TestMethod]
            public void TestMethod3()
            {
                a = 3;
                Assert.AreEqual(1, 1);
            }
        }

    So to achieve your requirement, you need to take Tim's advice to create two test classes. 

    Best Regards,

    Lake Xiao


    • Edited by lake Xiao Wednesday, September 7, 2016 7:55 AM
    Wednesday, September 7, 2016 7:54 AM
  • Thank you Tim!
    Thursday, September 8, 2016 5:25 AM
  • Sure. Thank you!
    Thursday, September 8, 2016 5:25 AM