Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 650
Stefan de Kok Avatar asked Sep 20 '12 20:09

Stefan de Kok


People also ask

Does TestInitialize run for each test?

TestInitialize and TestCleanup are ran before and after each test, this is to ensure that no tests are coupled. If you want to run methods before and after ALL tests, decorate relevant methods with the ClassInitialize and ClassCleanup attributes.

What is TestInitialize Mstest?

The method decorated by [TestInitialize] is called before running each test of the class. The method decorated by [TestCleanup] is called after running each test of the class.

What is TestInitialize C#?

TestInitialize. This attribute is needed when we want to run a function before execution of a test. For example we want to run the same test 5 times and want to set some property value before running each time. In this scenario we can define one function and decorate the function with a TestInitialize attribute.

What is ClassInitialize?

ClassInitialize runs only on the initialization of the class where the attribute is declared. In other words it won't run for every class. Just for the class that contains the ClassInitialize method. If you want a method that will run once before all tests or classes' initialization use the AssemblyInitialize .


1 Answers

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.

like image 113
Stefan de Kok Avatar answered Sep 25 '22 12:09

Stefan de Kok