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?
To test that a constructor does its job (of making the class invariant true), you have to first use the constructor in creating a new object and then test that every field of the object has the correct value. Yes, you need need an assertEquals call for each field.
TestInitialize and TestCleanup are ran before and after each test, this is to ensure that no tests are coupled. If you want to run methods before and after ALL tests, decorate relevant methods with the ClassInitialize and ClassCleanup attributes.
TestInitialize. This attribute is needed when we want to run a function before execution of a test. For example we want to run the same test 5 times and want to set some property value before running each time. In this scenario we can define one function and decorate the function with a TestInitialize attribute.
ClassInitialize runs only on the initialization of the class where the attribute is declared. In other words it won't run for every class. Just for the class that contains the ClassInitialize method. If you want a method that will run once before all tests or classes' initialization use the AssemblyInitialize .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With