Trung Nguyen
Trung Nguyen

Reputation: 31

How to initialize some tests and not others?

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?

Upvotes: 2

Views: 266

Answers (3)

chaliasos
chaliasos

Reputation: 9783

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; }
}

Upvotes: 0

Dennis Traub
Dennis Traub

Reputation: 51634

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.

Upvotes: 1

Tejs
Tejs

Reputation: 41236

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.

Upvotes: 2

Related Questions