Quick question, I'm using the Visual Studio's testing framework for unit testing. Just wondering what's the difference between using the constructor to do initialization work vs. having a method with [TestInitialize()] attribute?
-
1possible duplicate of [Do you use TestInitialize or the test class constructor to prepare each test? and why?](http://stackoverflow.com/questions/334515/do-you-use-testinitialize-or-the-test-class-constructor-to-prepare-each-test-and) – mafu Sep 16 '10 at 22:39
3 Answers
This post gives an overview of the different methods. As you can see, the ctor is called immediately before the ClassInitialize
(only once, of course) and TestInitialize
.
So put stuff that requires code in ClassInitialize
in your TestInitialize
method. Everything that should be set up before ClassInitialize
goes in the ctor.
Obviously, TestInitialize
content will be executed once before each test. The corresponding method to close after each test is TestCleanup
. For classes, use ClassCleanup
. The same thing exists for assemblies as well (AssemblyInitialize/Cleanup
).

- 2,805
- 2
- 35
- 58

- 31,798
- 42
- 154
- 247
-
7Your first two sentences are incorrect. The ctor is called before each test (which gets its own instance). `ClassInitialize` is called (once) before any ctor (and hence any test) - this is why it has to be static! – Ohad Schneider Jul 23 '17 at 22:16
Conceptually they are they same, as MSTest creates a new instance of your test class before each test execution. However, technically there are a few differences:
- The ctor is called before
TestInitialize
(no surprise as the latter is an instance method). - You have access to
TestContext
inTestInitialize
. - More inheritance scenarios are enabled with
TestInitialize
: https://stackoverflow.com/a/8689398/67824. - You can assign
readonly
fields in the ctor. I think it's pretty important: https://stackoverflow.com/a/45270180/67824.

- 36,600
- 15
- 168
- 198
The ctor
is for initializing the object.
TestInitialize
is for initializing any objects or data needed to run the test.

- 1,856
- 2
- 29
- 46
-
5But given that the object you're constructing is a test class, surely the only thing you would be initialising in that constructor are objects or data needed to run the test... – bacar Aug 20 '11 at 14:09
-
2To clarify, TestInitialize runs before each test, so if you initialize objects here, they'll be re-created for each test. This is good practice. Otherwise, the same object would be shared in all tests in the class, a big no-no in unit testing. – Josh Noe Jul 21 '13 at 22:29