Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TestInitialize vs ClassInitialize

What is the difference between TestInitialize vs ClassInitialize in MSTest? What are the pros cons of each?

I'm under the impression that TestInitialze should run with EACH test, every time? Is that correct? And that ClassInitialize will run every time a new instance of any class?

like image 843
snowmom475 Avatar asked Apr 10 '14 21:04

snowmom475


People also ask

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 .

What is TestInitialize Mstest?

The method decorated by [TestInitialize] is called before running each test of the class. The method decorated by [TestCleanup] is called after running each test of the class.

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.


1 Answers

Both attributes are available only for the classes (and hence tests) where they belong.

TestInitialize runs before every test that is declared on the the same class where the attribute is declared.

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.

like image 62
chaliasos Avatar answered Oct 03 '22 23:10

chaliasos