How do you test private methods with NUnit?

后端 未结 13 2434
春和景丽
春和景丽 2020-12-02 16:00

I am wondering how to use NUnit correctly. First, I created a separate test project that uses my main project as reference. But in that case, I am not able to test private m

13条回答
  •  甜味超标
    2020-12-02 16:49

    While I agree that the focus of unit testing should be the public interface, you get a far more granular impression of your code if you test private methods as well. The MS testing framework allows for this through the use of PrivateObject and PrivateType, NUnit does not. What I do instead is:

    private MethodInfo GetMethod(string methodName)
    {
        if (string.IsNullOrWhiteSpace(methodName))
            Assert.Fail("methodName cannot be null or whitespace");
    
        var method = this.objectUnderTest.GetType()
            .GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance);
    
        if (method == null)
            Assert.Fail(string.Format("{0} method not found", methodName));
    
        return method;
    }
    

    This way means you don't have to compromise encapsulation in favour of testability. Bear in mind you'll need to modify your BindingFlags if you want to test private static methods. The above example is just for instance methods.

提交回复
热议问题