简体   繁体   中英

C# Testing - Is [ClassInitialize] guaranteed to run only after previous tests are finished?

I'm using [ClassInitialize] and [ClassCleanup] tags from Microsoft.VisualStudio.TestTools.UnitTesting. MSTest 2.0

I have a test class with tests that require my app to be in a different mode than usual.

I turn the mode on in [ClassInitialize] and off in [ClassCleanup] .

This doesn't work, as I learned from a comment to this answer : there's no guarantee that the execution of [ClassCleanup] happens before any other tests are started. This is bad because in another class i have tests that require for the mode to be turned off. The mode doesn't get turned off in time and they fail.

I could turn the mode on/off for every test individually, but this is the very last option, because it takes a lot of time.

I could move the class to it's own assembly, but i don't really want to do that either.

I fixed it by turning the mode off in [ClassInitialize] of the class that requires it to be off.

But i need to know, does [ClassInitialize] share the same unintuitive behavior with [ClassCleanup] , or is it guaranteed to NOT run before any previous tests are finished? That would make the first tests fail.

The very best solution would be to somehow force [ClassCleanup] to run immediately after the first test class is all finished, but that's probably not possible.

From what I've learned so far the answer is YES .

You CAN count on [ClassInitialize] to not run sooner than necessary. (as opposed to [ClassCleanup] running later)

However, my tests (when I run all) do not jump back and forth between test classes , I can only imagine how it would pan out then. Then you really wouldn't wanna use [ClassCleanup] and [ClassInitialize] in a way they could interfere with each other (eg turning on/off special mode).

If your test runner does leapfrog between test classes, I would move sensitive tests to different assemblies and use [AssemblyCleanup] / [AssemblyInitialize].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM