获取视图名在ViewResult.ViewName是单元测试空字符串 [英] Get View Name where ViewResult.ViewName is empty string for Unit Testing

查看:474
本文介绍了获取视图名在ViewResult.ViewName是单元测试空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写的扩展方法上的ActionResult在单元测试使用,这将断言是否VIEWNAME返回的是预期。这是code我到目前为止有:

I have written an extension method on ActionResult for use in unit testing which will assert whether the ViewName returned is what was expected. This is the code I have so far:

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 是一个空字符串

This works fine except where the controller returns a View without specifying a name - in this case result.ViewName is an empty string.

所以,我的问题是 - 有从的ViewResult告诉任何水井对象怎么办视图的名字是在哪里VIEWNAME是一个空字符串

So, my question is - is there any well of telling from a ViewResult object what the name of the View was where ViewName is an empty string?

推荐答案

如果您的控制器方法不是通过MVC管道调用,其他信息不添加到 Controller.ViewData 词典(我假定会以某种方式提供了一个行动 - 键,但无法证实)。但是,由于您使用的控制器外部路由框架等情况下是没有办法它知道调用的方法。

If your controller-method is not called through the MVC pipeline, additional information are not added to the Controller.ViewData dictionary (which I assumed would somehow provide an "action"-key, but couldn't confirm). But since you using your controller "outside" the context of the routing-framework etc. there is no way it knows about the called method.

因此​​,答案是简单的不。如果没有指定视图的名字,你不能从操作返回的ViewResult确定它。至少不会在控制器被测试的方式(这是完全正常的方式)。

So the answer is simply "no". If the name of the view was not specified, you cannot determine it from the ViewResult returned by the action. At least not in the way your controller is being tested (which is totally fine by the way).

这篇关于获取视图名在ViewResult.ViewName是单元测试空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆