26

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?

Ray
  • 12,101
  • 27
  • 95
  • 137
  • 1
    possible 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 Answers3

10

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).

Further reading

Steffen Winkler
  • 2,805
  • 2
  • 35
  • 58
mafu
  • 31,798
  • 42
  • 154
  • 247
  • 7
    Your 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
9

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:

  1. The ctor is called before TestInitialize (no surprise as the latter is an instance method).
  2. You have access to TestContext in TestInitialize.
  3. More inheritance scenarios are enabled with TestInitialize: https://stackoverflow.com/a/8689398/67824.
  4. You can assign readonly fields in the ctor. I think it's pretty important: https://stackoverflow.com/a/45270180/67824.
Ohad Schneider
  • 36,600
  • 15
  • 168
  • 198
2

The ctor is for initializing the object.

TestInitialize is for initializing any objects or data needed to run the test.

morganpdx
  • 1,856
  • 2
  • 29
  • 46
  • 5
    But 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
  • 2
    To 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