85

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?

Jim Aho
  • 9,932
  • 15
  • 56
  • 87
snowmom475
  • 967
  • 1
  • 6
  • 7

2 Answers2

118

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.

chaliasos
  • 9,659
  • 7
  • 50
  • 87
  • 4
    What would be a usecase of ClassInitialize and AssemblyInitialize? I have a hard time to get an actual usecase for ClassInitialize... – Ini Nov 28 '17 at 17:21
  • 3
    One use case is when running integration tests for a DLL with an initialization method that takes a long time to run. ClassInitialize can be used to perform initialization at the start of the batch of tests, and ClassCleanup would call the DLL's terminate method. – user8550137 Mar 26 '18 at 20:07
  • Another case could be setting up objects with tons of injected dependencies and mock set-ups. I have some test classes with 100+ lines that would otherwise need to be in each test. – DPH Nov 30 '18 at 13:50
  • 3
    @DPH TestInitialize is good for repeated code, only if running the code takes long time, you will use ClassInitialize – Michael Freidgeim Jan 11 '19 at 06:54
0

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

Кое Кто
  • 445
  • 5
  • 9