Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing a private field using MSTest

Tags:

c#

mstest

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

like image 835
Michelle Avatar asked May 28 '12 19:05

Michelle


People also ask

Can you test private methods?

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.

How do I run a MSTest unit test?

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.

Is MSTest a testing framework?

MSTest framework for Selenium automated testing is the default test framework that comes along with Visual Studio.


2 Answers

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.

like image 112
Mike Zboray Avatar answered Sep 29 '22 13:09

Mike Zboray


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);
    }
}
like image 36
Regianni Avatar answered Sep 29 '22 11:09

Regianni