Question

Background: I have a bunch of unit tests in .NET that require some configuration data to be set up in order to run. Initially, I was using TestInitialize and TestCleanup to set up and tear down the configuration data around each test; however, a single setup is sufficient for the entire suite of tests, so I would prefer to use ClassInitialize and ClassCleanup instead.

Problem: When I change the attribute from TestInitialize to ClassInitialize and run the tests, I get the following error:

MyTestClass.ClassInit has wrong signature. The method should be marked static.

What are the design reasons behind this attribute requiring its method to be static? All of my test methods are instance methods, so I would assume there's at least one instance of my test class being created somewhere in order to run them. Why would that instance not be in charge of cleaning up afterward?

I did check MSDN, and they don't explicitly mention the static requirement, although they do have a good example of its usage.

Was it helpful?

Solution

As MSDN states the ClassInitializeAttribute

Identifies a method that contains code that must be used before any of the tests in the test class have run and to allocate resources to be used by the test class. This class cannot be inherited.

one example that I can think about where this can come in hand, is when you have a static field in your class that the constructor of the instances depends on.

class foo
{
  static someObject bar;
  int foobar;

  public foo()
  {
    this.foobar = foo.bar.SomeMethod()
  }
}

this way in your ClassInitializeAttribute method you can assign a value to the static bar object, which will effect all the instances created later on.

Another case you might want to use the ClassInitializeAttribute is for assigning global objects that the test might use (such as a mock database etc.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top