在我的一个单元测试中,我想检查是否所有公共(public)方法都返回 ActionResult 类型。这是我的测试方法:
[TestMethod]
public void Public_Methods_Should_Only_Return_ActionResults()
{
MethodInfo[] methodInfos = typeof(MyController).GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
foreach (MethodInfo methodInfo in methodInfos)
{
Assert.IsInstanceOfType(methodInfo.ReturnType, typeof(System.Web.Mvc.ActionResult));
}
}
这个测试在 MyController 的第一个方法上失败了:
[Authorize]
public ActionResult MyList()
{
return View();
}
出现以下错误:
Assert.IsInstanceOfType failed. Expected type:<System.Web.Mvc.ActionResult>. Actual type:<System.RuntimeType>.
当我在该 Assert 上设置断点并检查 methodInfo.ReturnType 时,它的类型是 Type,并且是 ActionResult。
谁能解释一下为什么测试会失败,以及如何才能让它发挥作用?
提前致谢, 先生
最佳答案
使用 Assert.AreEqual 而不是 Assert.IsInstanceOfType。您想检查结果的类型,而不是反射(reflect)的类型信息的类型。
关于c# - C# 单元测试中的 RuntimeType 而不是 Type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1209339/