私有方法的单元测试c#

时间:2017-08-08 08:13:20

标签: c# unit-testing

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

public abstract class BaseAPI
{
    private void CheckWarehouseAvailability(Order order)
    {
        //codes here
    }
}

public class Processor : BaseAPI
{

}

这是我的TestMethod

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

2 个答案:

答案 0 :(得分:3)

您需要实例化Order的{​​{1}}参数并将其作为参数传递给CheckWarehouseAvailability

PrivateObject.Invoke()
  

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

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

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

...因为Assert.AreEqual(true, retVal); 将其返回类型设置为CheckWarehouseAvailability,而不是void

答案 1 :(得分:1)

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

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

然后用你的参数调用方法

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