Classes marked with TestInitialize and TestCleanup not executing

Stefan de Kok picture Stefan de Kok · Sep 20, 2012 · Viewed 23.3k times · Source

I have been struggling with this one, hopefully it will help someone else.

Whilst creating unit tests using MsTest I discovered I was repeating the same code in each test, and found a couple of handy attributes (TestInitialize, TestCleanup, ClassInitialize, and ClassCleanup).

Supposedly, when you mark a method with one of these attributes, it should execute automatically (prior to each test, after each test, prior to all tests, and after all tests respectively). Frustratingly, this did not happen, and my tests failed. If directly calling these methods from the classes marked with TestMethod attribute, the tests succeeded. It was apparent they weren't executing by themselves.

Here is some sample code I was using:

[TestInitialize()]
private void Setup()
{
    _factory = new Factory();
    _factory.Start();
}

So why is this not executing?

Answer

Stefan de Kok picture Stefan de Kok · Sep 20, 2012

The trick is to make these methods public:

[TestInitialize()]
public void Setup()
{
    _factory = new Factory();
    _factory.Start();
}

When they are private they do not execute.