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?
views:
81answers:
3The method marked as [TestInitialize] can have any name you want, so you can be explicit what this particular method is doing.
I haven't tested it, but I think you can have multiple [TestInitialize] methods, so you can initialize different aspects of your tests in different methods (someone please correct me if I am wrong here).
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
).
The ctor
is for initializing the object.
TestInitialize
is for initializing any objects or data needed to run the test.