Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MSTest ClassInitialize once for entire class

ClassInitialize seems to be getting called for every test. I guess it is because a new class is actually created for every test.

Why? Every other framework doesn't do this!

Anyways... I need to execute one method (not static) on the class. I also need to execute all the test methods within the same instance of the class.

Am I up a creek without a paddle?

like image 861
Paul Knopf Avatar asked Jul 19 '12 17:07

Paul Knopf


1 Answers

ClassInitialize is called once by MSTest before any of the TestMethods are invoked, see remarks here. TestInitialize is called once before each test method. MSTest creates a new instance of the test class for each TestMethod call. This is why ClassInitialize is a static method.

I need to execute one method (not static) on the class. I also need to execute all the test methods within the same instance of the class.

Do you mean you need to execute one method on the TestClass or the class under test (the class you are actually testing)?

In either case, you can have a static member in the TestClass and initialize it once in ClassInitialize. It will be created only once and exist for the lifetime of your tests. You can invoke a method on it only once. You can then use this single instance in each of your test methods.

One thing to be aware of is that MSTest may interleave tests from different classes. So if you have any global mutable state which is accessed from more than one ClassInitialize (or test for that matter), unpredictable things might happen. For that reason, statics are best avoided.

The requirement that all methods must be executed on the same instance is quite unusual. Perhaps there is a way to refactor your code to eliminate this constraint?

like image 101
Alex Peck Avatar answered Sep 16 '22 22:09

Alex Peck