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