20

Is it possible to get access to a private static field inside a static class, using the VS2010 Unit Test class PrivateObject ?

Let say i have the following class:

public static class foo
{
    private static bar;
}

Can i use PrivateObject to create a copy of foo, and then get the bar field?

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
Yiftach Tzur
  • 275
  • 4
  • 8

3 Answers3

32

PrivateType class is analogous to PrivateObject for invoking private static members. Overloaded GetStaticFieldOrProperty methods may be used. http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.privatetype(v=VS.100).aspx

Deepum
  • 321
  • 3
  • 4
9

The answer by Deepun can be very useful. I wanted to add a specific example to help people who come this way.

Class with private static member.

public class foo
{
   private static int bar;
}

Code to get value.

PrivateType pt = new PrivateType(typeof(foo));
int bar = (int)pt.GetStaticFieldOrProperty("bar");

Code to change value

PrivateType pt = new PrivateType(typeof(foo));
pt.SetStaticFieldOrProperty("bar", 10);

This will work regardless of the class being static or not.

denver
  • 2,863
  • 2
  • 31
  • 45
7

The property value can be retreived using reflection. This will require the use of Type.GetField Method (String, BindingFlags) and the FieldInfo.GetValue Method

string propertyName = "bar";
FieldInfo fieldInfo = typeof(foo).GetField(propertyName, BindingFlags.NonPublic | BindingFlags.Static);
object fieldValue = fieldInfo.GetValue(null);
Devendra D. Chavan
  • 8,871
  • 4
  • 31
  • 35