Unit Testing a Static Class

I’ve been trying to find a way to unit test a static class. That is, a class that has no instances. The problem has been that at the end of one test the class’s state could be altered which would mean that at the start of the next test its state would be unknown. This could lead to buggy unit tests.

The solution, I’ve found, is to invoke the type initialiser (sometimes known as the “class initialiser”, “static initialiser”, “static constructor” or “class constructor”) using reflection and ensure that all fields are set up there. That way, each unit test run will be starting the static class with a clean state and it no longer matters what the unit test does.

The code to invoke the type initialiser:

Type staticType = typeof(StaticClassName);
ConstructorInfo ci = staticType.TypeInitializer;
object[] parameters = new object[0];
ci.Invoke(null, parameters);


NOTE: This blog entry was rescued from the Google Cache. It was originally dated Monday 7th May, 2007.

There was one comment of note:

If you have a static class with state, then you have a singleton – generally to be avoided, but sometimes unavoidable. One way to think of singletons is as services – they provide a service to your app. Services usually interact with the outside world in some way, so for testing purposes it is useful to be able to switch between a real implementation and a Mock one.

So the trick that I use is to create a singleton service locator class, with a manual switch for changing from Test mode to Normal mode. Fowler calls this the Registry pattern in PoEAA.

5/8/2007 6:38 PM | Steve Campbell

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s