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?
ClassInitialize
is called once by MSTest before any of the TestMethod
s 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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With