Stefan de Kok
Stefan de Kok

Reputation: 2029

Classes marked with TestInitialize and TestCleanup not executing

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?

Upvotes: 45

Views: 25717

Answers (3)

seawave_23
seawave_23

Reputation: 1248

I also had the problem and - due to my misunderstanding of how the methods get called - solved it with this: Make your tests inherit from the class containing the TestInitialize and TestCleanup methods.

Upvotes: 1

Stefan de Kok
Stefan de Kok

Reputation: 2029

TestInitialize and TestCleanup are run before and after all the tests, not before and after each one.

That is wrong, see for example this link: http://social.msdn.microsoft.com/Forums/en-US/vststest/thread/85fb6549-cbaa-4dbf-bc3c-ddf1e4651bcf

See also MSDN

http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.classinitializeattribute.aspx

The example code shows how to use TestInitialize, ClassInitialize, and AssemblyInitialize.

Upvotes: 9

Stefan de Kok
Stefan de Kok

Reputation: 2029

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.

Upvotes: 118

Related Questions