Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between using the constructor in VS Testing framework vs. TestInitialize() attribute?

Tags:

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?

like image 931
Ray Avatar asked Jun 21 '10 17:06

Ray


People also ask

How do you test a constructor class?

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.

Does TestInitialize run for each test?

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.

What is TestInitialize C#?

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.

What is ClassInitialize?

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 .


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

Further reading

like image 57
mafu Avatar answered Sep 27 '22 19:09

mafu