Why must a ClassInitialize method be static?

ProfK picture ProfK · Aug 26, 2012 · Viewed 17.8k times · Source

I'm curious as to why the fixture setup must be static? It seems more intuitive to me to have instance variables per fixture that share the lifetime of the fixture.

Yes, these can be initialized in the constructor, but then I assume they are out of reach of the control of the test runner.

What design requirements or philosophies determined that the setup method should be static?

Answer

Stephen Oberauer picture Stephen Oberauer · Aug 26, 2012

The method with the ClassInitialize attribute runs once for all the tests in the class. An instance of the class is created each time a test is run, so it has to be static in order to only run once.

If you want to initialize for every test, then you can use the TestInitialize attribute, which will run whenever a new instance of the class is created (before running a test).

If you need more info, you can check out:

That Pesky MSTest Execution Ordering