Superbest
Superbest

Reputation: 26612

private TestInitialize method is not initializing objects

I have a test class that should basically be like the following:

[TestClass]
public class MyTest
{
    private MyClass o1;
    private MyClass o2;

    [TestInitialize]
    private void PrepareObjects()
    {
        o1 = new MyClass();
        o2 = new MyClass();
    }

    [TestMethod]
    public void TestEquality()
    {
        Assert.IsTrue(o1.Equals(o2));
    }        
}

But when I run the tests, I get a NullReferenceException. If I put breakpoints inside PrepareObjects and TestEquality then I can see that TestInitialize has not been invoked by the time TestEquality is.

Changing PrepareObjects from private to public fixes this. Why?

Upvotes: 18

Views: 4185

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062955

The test framework is only looking for public methods. Similarly, if you make TestEquality private, that won't run, and if you make MyTest internal, then nothing shown will run.

Upvotes: 31

Related Questions