C# – Using ClassInitialize in a test class

When you want to initialize something for all unit tests in a test class, you can apply the ClassInitialize attribute to a method. This initialization method only runs once and is ran before any of the unit tests. Here’s an example of how to add ClassInitialize:

using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass()] public class CalculatorTests { [ClassInitialize] public static void TestClassInit(TestContext context) { //Initialize something for all tests } [ClassCleanup] public static void TestClassCleanup() { //The opposite of ClassInitialize } [TestMethod] public void SomeTest() { //test here } }
Code language: C# (cs)

Note: ClassCleanup is the opposite of ClassInitialize. It runs once after all the tests have finished running.

ClassInitialize method requirements

You can only use ClassInitialize on a method with a very specific signature, otherwise it results in a runtime error and the tests won’t run. In the Test Runner, the tests will appear in a Not Run state (with a blue icon). You can look in the Output > Tests window and see following error:

Method TestClassInit has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be Task.

The solution is to change the method to meet ClassInitialize’s requirements: public static void with a single TestContext parameter, like this:

[ClassInitialize] public static void TestClassInit(TestContext context) { //Initialize something for all tests }
Code language: C# (cs)

After you fix the method signature, the tests will run.

2 thoughts on “C# – Using ClassInitialize in a test class”

  1. “The solution is straightforward: change the method to meet the requirements and then the tests will run.”

    😐

    Why do you do this to us?

    Reply

Leave a Comment