TestInitialize vs ClassInitialize

What is the difference between TestInitialize vs ClassInitialize in MSTest? What are the pros cons of each?

I'm under the impression that TestInitialze should run with EACH test, every time? Is that correct? And that ClassInitialize will run every time a new instance of any class?

44422 次浏览

Both attributes are available only for the classes (and hence tests) where they belong.

TestInitialize runs before every test that is declared on the the same class where the attribute is declared.

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.

Since ClassInitialize and ClassCleanUp are static, they are only executed once even though several instances of a test class can be created by MSTest.

You can read more about it here: That Pesky MSTest Execution Ordering.. learn.microsoft.com