Search code examples
c#visual-studio-2012mstestprivate-members

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?


Solution

  • 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.