Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top