Search code examples
c#unit-testingmstestinitializer

Initialise unit test class members upon declaration or in the TestInitialize method?


I understand that, when running unit tests, the class is instantiated for each test method. Therefore, I see no difference in initialising members upon declaration versus in the TestInitialize method. Is there anything particularly wrong about doing the former?

Note that this is a different question to TestInitialize vs ClassInitialize, although it technically might be similar.


Solution

  • No, there is nothing wrong with initializing members in the declaration.

    Primarily it comes down to preferred style. I prefer to make as many members readonly as I can, so I prefer initializing in the declaration when possible.

    Others may prefer use of setup/teardown methods for all initialization and cleanup logic.