Search code examples
c#unit-testingmstest

Why is [TestClass]'s constructor called multiple times for each [TestMethod]?


In case of you have multiple test method on a test class. Class's constructor is going to run multiple times. How we can explain this overload?


Solution

  • From my understanding of MSTest, the test class gets instantiated for each [TestMethod]. I'm guessing you are attempting to run configuration code before any of the tests are ran. If that's the case I'd recommend you:

    A) update your question to explain what it is exactly you would like to accomplish

    B) make use of the [ClassInitialize] attribute to mark a method to be ran once and only once before any of the class's tests are ran

    What Does ClassInitialize Do

    ClassInitialize is one of the many attributes available when using MSTest to write unit tests in C#. The more common ones include TestClass, TestMethod, and TestInitialize. This one indicates that the method should be ran once before running any of the methods marked with TestMethod. There's another attribute that goes hand-in-hand with it called ClassCleanup which gets ran after all of the test methods get ran.

    You can read more details about these and more attributes at learn.microsoft.com