Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ClassInitialize attribute in unit test based class not called

I added these method in a TestBase class :

[ClassInitialize] public static void InitializBeforeAllTests() { } 

But when I run in Debug an unit test Test1() :

[TestClass] public class TestMapping : TestBase {     [TestMethod]     public void Test1()     {     } 

The TestBase.InitializBeforeAllTests() method is never called. Why?

like image 568
Phil Avatar asked Sep 06 '11 15:09

Phil


People also ask

What is ClassInitialize attribute in MS test?

The method decorated by [ClassInitialize] is called once before running the tests of the class. In some cases, you can write the code in the constructor of the class. The method decorated by [ClassCleanup] is called after all tests from all classes are executed.

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 .

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.


2 Answers

When declaring ClassInitialize attribute on a method, the method has to be static, public, void and should take a single parameter of type TestContext.

If you're having also other method with the AssemblyInitialize attribute on the same unit test, the test will run but will skip on all test methods and will go directly to AssemblyCleanup or just quit.

Try the example on ClassInitialize attribute in MSDN.

like image 124
Shaulian Avatar answered Oct 09 '22 07:10

Shaulian


You can setup an assembly initialize method in your base class. Not quite the same as ClassInitialize, but it's a viable option. Source:The Workaround mentioned here.

[TestClass] public abstract class TestBase {     [AssemblyInitializeAttribute]     public static void Initialize(TestContext context)     {         // put your initialize code here     } } 

You can also add a Cleanup method:

[AssemblyCleanup] public static void Cleanup() {    //clean up stuff here } 
like image 21
James Lawruk Avatar answered Oct 09 '22 05:10

James Lawruk