加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 获取视图名称,其中ViewResult.ViewName为单元测

发布时间:2020-12-16 03:41:35 所属栏目:asp.Net 来源:网络整理
导读:我在ActionResult上编写了一个扩展方法,用于单元测试,它将断言ViewName返回的是否是预期的.这是我到目前为止的代码: public static void AssertViewWasReturned(this ActionResult result,string viewName){ string actualViewName; if (result is ViewResu
我在ActionResult上编写了一个扩展方法,用于单元测试,它将断言ViewName返回的是否是预期的.这是我到目前为止的代码:

public static void AssertViewWasReturned(this ActionResult result,string viewName)
{
    string actualViewName;

    if (result is ViewResult)
        actualViewName = (result as ViewResult).ViewName;
    else if (result is PartialViewResult)
        actualViewName = (result as PartialViewResult).ViewName;
    else
        throw new InvalidOperationException("Results of type " + result.GetType() + " don't have a ViewName");

    Assert.AreEqual(viewName,actualViewName,string.Format("Expected a View named{0},got a View named {1}",viewName,actualViewName));
}

这工作正常,除非控制器返回视图而不指定名称 – 在这种情况下result.ViewName是一个空字符串.

所以,我的问题是 – 从ViewResult对象告诉ViewName是一个空字符串是什么?

解决方法

如果你的控制器方法没有通过MVC管道调用,则附加信息不会添加到Controller.ViewData字典中(我假设它会以某种方式提供“操作”-key,但无法确认).但是,由于您在路由框架等的上下文“外部”使用控制器,因此无法知道被调用的方法.

所以答案就是“不”.如果未指定视图的名称,则无法从操作返回的ViewResult中确定它.至少不是你的控制器的测试方式(顺便说一句,这完全没问题).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读