c# - C# 单元测试中的 RuntimeType 而不是 Type

标签 c# .net asp.net-mvc unit-testing reflection

在我的一个单元测试中,我想检查是否所有公共(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/

相关文章:

c# - 如何动态创建 lambda 表达式

c# - 如何在 .net Web 表单应用程序中放置画面报告

c# - 调试本地 IIS Web 服务器上托管的 ASP.NET MVC3 应用程序

c# - 密码加密/解密

c# - 如何使用 Microsoft.Azure.Search 搜索 ContinuationToken

c# - 从我的 Web 服务读取 Http POST 正文内容? (.net 3.5)

c# - 如何在列表中搜索距离小于 F 到 P 的项目而不搜索整个列表?

.net - 在 winforms 中丢弃 ui 事件的简单解决方案?

javascript - header无法使用跨域传入ajax

c# - HttpContext.Current.Cache 与 HttpRuntime.Cache