Search code examples
c#unit-testingtype-safetyprivateobject.invoke

How to create type safety on a PrivateObject in C#


I have discovered a fantastic way to unit test private methods.

This is great except I don't like how the method name is typed in as a string. Is there a way to create a "safety net?" I want to type the method name so that the compiler can throw a compiler time error if the method does not exist on an object.

Private method:

public class BankAccount
{
    //Private method to test
    private bool VerifyAmount(double amount)
    {
        return (amount <= 1000);
    }
}

Unit Test:

[TestMethod()]        
public void VerifyAmountTest()
{
    //Using PrivateObject class
    PrivateObject privateHelperObject = new PrivateObject(typeof(BankAccount));                             
    double amount = 500F;
    bool expected = true;
    bool actual;
    actual = (bool)privateHelperObject.Invoke("VerifyAmount", amount);            
    Assert.AreEqual(expected, actual);            
}

I know that some people think that we should not unit test private methods. That is not the purpose of this question so let's not discuss that question and stay on topic.


Solution

  • Am I right that you want check presence of private method on .Net object?

    Then pick one of the following cases to extract any method from instance:

    Case 1 If you don't care about method signature:

    var typeOfObj = typeof(BancAccount)
                   .GetMethods(
                     BindingFlags.NonPublic | 
                     BindingFlags.Instance)
                   .Any( method => method.Name == testedName )
    

    Case 2 If you need specify exact signature then use - typeof(BancAccount).GetMethod(testedName, <types of arguments>)