Private Field Testing with MSTest

Is it possible to access a private field in unit test?

+5
source share
3 answers

A way to get private fields or methods in general is to use Reflection. However, the unit test structure includes a helper class PrivateObjectto make this easier. See docs . In general, when I used this, I created extension methods, such as:

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, you will need to go with direct reflection.

+7
source

. Unit, - . , ( , ).

, Dependency Injection . .

+2

All Articles