私有方法的单元测试c#

Unit Test c# for Private Method

本问题已经有最佳答案,请猛点这里访问。

我需要在抽象类中测试CheckWarehouseAvailability私有方法。

1
2
3
4
5
6
7
8
9
10
11
12
public abstract class BaseAPI
{
    private void CheckWarehouseAvailability(Order order)
    {
        //codes here
    }
}

public class Processor : BaseAPI
{

}

这是我的TestMethod

1
2
3
4
Processor pro = new Processor();
PrivateObject privBase = new PrivateObject(pro, new PrivateType(typeof(BaseAPI)));
var retVal = privBase.Invoke("CheckWarehouseAvailability(order)");
Assert.AreEqual(true, retVal);

当我运行测试方法时,我收到此错误:An exception of type 'System.MissingMethodException' occured in mscorlib.dll but was not handled in user code


您需要实例化CheckWarehouseAvailabilityOrder参数并将其作为参数传递给PrivateObject.Invoke()

1
2
3
var order = new Order();
var retVal = privBase.Invoke("CheckWarehouseAvailability", order);
// ... Assert

MSDN: PrivateObject.Invoke(String, Object[])

另外,我不确定你在这里断言:

1
Assert.AreEqual(true, retVal);

...因为CheckWarehouseAvailability的返回类型设置为void,而不是bool


首先,您需要通过反射获取方法

1
2
MethodInfo methodName = privBase.GetType().GetMethod("ShowGrid",
           BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

然后用你的参数调用方法

1
var retVal=methodName .Invoke(privBase, order);