Testing a private field using MSTest

The way to get private fields or methods in general is to use Reflection. However, the unit test framework includes a helper class, PrivateObject, to make this easier. See the docs. In general, when I've used this, I've ended up making an extension methods like the following:

public static int GetPrivateField(this MyObject obj)
{
  PrivateObject po = new PrivateObject(obj);
  return (int)po.GetField("_privateIntField");
}

If you need to get private fields in a static class, however, you will need to go with straight up reflection.

Tags:

C#

Mstest