How do you unit test private methods?

前端 未结 30 1485
无人及你
无人及你 2020-11-22 06:44

I\'m building a class library that will have some public & private methods. I want to be able to unit test the private methods (mostly while developing, but also it coul

30条回答
  •  逝去的感伤
    2020-11-22 07:41

    For anyone who wants to run private methods without all the fess and mess. This works with any unit testing framework using nothing but good old Reflection.

    public class ReflectionTools
    {
        // If the class is non-static
        public static Object InvokePrivate(Object objectUnderTest, string method, params object[] args)
        {
            Type t = objectUnderTest.GetType();
            return t.InvokeMember(method,
                BindingFlags.InvokeMethod |
                BindingFlags.NonPublic |
                BindingFlags.Instance |
                BindingFlags.Static,
                null,
                objectUnderTest,
                args);
        }
        // if the class is static
        public static Object InvokePrivate(Type typeOfObjectUnderTest, string method, params object[] args)
        {
            MemberInfo[] members = typeOfObjectUnderTest.GetMembers(BindingFlags.NonPublic | BindingFlags.Static);
            foreach(var member in members)
            {
                if (member.Name == method)
                {
                    return typeOfObjectUnderTest.InvokeMember(method, BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.InvokeMethod, null, typeOfObjectUnderTest, args);
                }
            }
            return null;
        }
    }
    

    Then in your actual tests, you can do something like this:

    Assert.AreEqual( 
      ReflectionTools.InvokePrivate(
        typeof(StaticClassOfMethod), 
        "PrivateMethod"), 
      "Expected Result");
    
    Assert.AreEqual( 
      ReflectionTools.InvokePrivate(
        new ClassOfMethod(), 
        "PrivateMethod"), 
      "Expected Result");
    

提交回复
热议问题