This is a mirror of official site: http://jasper-net.blogspot.com/

Invoking the Static Constructor via Reflection

| Monday, June 21, 2010
-- Warning! --
This post may cause the reader a slight feeling of nausea. However, remember that tough situations call for some tough actions!

The Situation

Imagine that you have to write some-unit tests for a class which uses an existing infrastructure, involving calls to static methods on a static class. To make things worse, this static class also holds some state which, unfortunately, gets carried around between tests without no actual ability to clear it.

   public static class MyInfrastructureClass
   {
       private static Dictionary<int, string> _someState =
           new Dictionary<int, string>();
       private static List<double> _someOtherState = new List<double>();

       public static void SomeOperation1()
       {
           // ...
       }

       public static void SomeOperation2()
       {
           // ...
       }
   }
After a unit-test is run, the state of the above class is not fresh, and as a result unit-tests can influence each-other and their success is dependant on the order in which they are run. This is obviously a very bad situation to be in.

Possible Solution

If there is no inherent built-in way to clear the state of the static class, then one can think of two possible solutions:

Add a “Reset()”-like static method especially for unit-tests which is responsible of reinitializing the class’ state. While this solution is feasible, it involves writing special code for unit-tests which has to be maintained, and if the static class’ code is not yours this is not possible in the first place.
Dynamically invoke the static constructor via reflection – this is the solution I would like to demonstrate.

Read more: Stiller's Blog

Posted via email from .NET Info

0 comments: