Is it possible to get access to a private field in a unit test?
To test private methods, you just need to test the public methods that call them. Call your public method and make assertions about the result or the state of the object. If the tests pass, you know your private methods are working correctly.
To run MSTest unit tests, specify the full path to the MSTest executable (mstest.exe) in the Unit Testing Options dialog. To call this dialog directly from the editor, right-click somewhere in the editor and then click Options.
MSTest framework for Selenium automated testing is the default test framework that comes along with Visual Studio.
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.
Nice solution offered above. For completeness, I have been using this technique for a while now (using MSTest), but have extended it for property values also.
[ExcludeFromCodeCoverage]
public static class TestExtensionMethods
{
public static T GetFieldValue<T>(this object sut, string name)
{
var field = sut
.GetType()
.GetField(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
return (T)field?.GetValue(sut);
}
public static T GetPropertyValue<T>(this object sut, string name)
{
var field = sut
.GetType()
.GetProperty(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
return (T)field?.GetValue(sut);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With