Blog Logo

Unit Testing a Static Class

16 Jun 2007 ~ 1 min read


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);

Ideally, you’d probably want to create the static class as a singleton and have your dependency injection framework resolve it in your application. Then you can create new instances of it in your test to be able to effectively reset the state each test. However, this is not always possible, especially in old or legacy applications.


Headshot of Colin Mackay

Hi, I'm Colin. I'm a software engineer with over 30 years of experience based in central Scotland, specialising in Microsoft technologies, initially with C++ and then in C#. I was a Microsoft MVP from 2007 to 2010 and a Code Project MVP from 2005 to 2009.