2

Using TestInitialize(), I can initialize all the tests in the TestClass. But if I want only some tests to be initialize and not others, how can I achieve this?

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459

3 Answers3

2

Move the non-shared initialization of test data to each [TestMethod] method.

The initialization method is called once for each test, so simply move code you dont want run for all tests into the specific methods.

Tejs
  • 40,736
  • 10
  • 68
  • 86
1

You can achieve this by separating them into two classes. Or, if they both use the same methods and variables, put them into subclasses that inherit from a common base class with shared methods and data.

Dennis Traub
  • 50,557
  • 7
  • 93
  • 108
0

The best way is to separate your Test Methods into different Test Classes. However If you want to have them all in one Test Class you can create different initialization methods for each test:

[TestClass]
public class TestClass
{
    [TestInitialize]
    public void Initialize()
    {
        switch (TestContext.TestName)
        {
            case "TestMethod1":
                this.InitializeTestMethod1();
                break;

            case "TestMethod2":
                this.InitializeTestMethod2();
                break;

            default:
                break;
        }
    }

    [TestMethod]
    public void TestMethod1()
    {
    }

    [TestMethod]
    public void TestMethod2()
    {
    }

    private void InitializeTestMethod1()
    {
        // Initialize TestMethod1
    }

    private void InitializeTestMethod2()
    {
        // Initialize TestMethod2
    }

    public TestContext TestContext { get; set; }
}
chaliasos
  • 9,659
  • 7
  • 50
  • 87