运行时类型而不是C#单元测试中的类型

Mic*_*ski 7 .net c# reflection asp.net-mvc unit-testing

在我的一个单元测试中,我想检查所有公共方法是否都返回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));

        }

    }
Run Code Online (Sandbox Code Playgroud)

这个测试爆炸了MyController的第一个方法:

[Authorize]
public ActionResult MyList()
{
    return View();
}
Run Code Online (Sandbox Code Playgroud)

出现以下错误:

Assert.IsInstanceOfType failed. Expected type:<System.Web.Mvc.ActionResult>. Actual type:<System.RuntimeType>.  
Run Code Online (Sandbox Code Playgroud)

当我在Assert上设置断点并检查methodInfo.ReturnType时,它的类型为Type,它是ActionResult.

任何人都可以解释为什么测试正在爆炸以及如何使其发挥作用?

先谢谢,MR

Cra*_*ntz 13

使用Assert.AreEqual而不是Assert.IsInstanceOfType.您想要检查结果的类型,而不是反映的类型信息的类型.