在我的家庭控制器中,我有以下内容:

 public ActionResult Index()
 {
     SetModuleTitle("Welcome");

     return RedirectToAction( "DashBoard", "Home" );       
 }

setModuletitle在父类中定义为:

public void SetModuleTitle(string title)
{
    ViewData["ModuleTitle"] = string.Format("PM4 - {0}", title);
}

没有什么人对此感到困惑。现在,我正在尝试编写测试以测试SetModuletitle方法:

 [Subject( typeof( HomeController ) )]
public class when_the_home_page_is_requested_by_logged_in_user_ : context_for_a_home_controller_for_logged_user
{
    static ActionResult result;

    Because of = () => result = HomeController.Index();

    It should_set_the_module_title = () => ( ( ViewResult ) result ).ViewData[ "ModuleTitle" ].ShouldEqual( "PM4 - Dashboard" );      
}

我正确地被告知

无法施放类型的对象“ system.web.mvc.redirecttorouteresult” tote'system.web.mvc.viewresult'。

那么,在这种情况下,我将如何设置MSPEC测试?

大卫

有帮助吗?

解决方案

好的,我认为我知道我出了什么问题。但是,首先我必须提供由

返回redirecttoaction(“仪表板”,“ home”);

public ActionResult DashBoard()
    {
        SetModuleTitle("Dashboard");

        return View();
    }

因此,如果我的理解是正确的,则在我的测试打电话后

因为=()=>结果= homecontroller.index();

返回REDIRECTTOACTION对象,并且代码执行停止在那里,即它不调用RedirectToAction中指定的控制器方法。这是有道理的,因为毕竟我们在这里做的是单元测试而不是集成测试。因此,在此处测试SetModuletitle方法是没有意义的。

相反,应实现测试调用方法仪表板的代码:

[Subject(typeof(HomeController))]
public class when_the_dashboard_page_is_requested_by_logged_in_user : context_for_a_home_controller_for_logged_user
{
    static ActionResult result;

    Because of = () => result = HomeController.DashBoard();

    It should_set_the_module_title = () =>
        {
            ( ( ViewResult ) result ).ViewData[ "ModuleTitle" ].ShouldEqual( "PM4 - Dashboard" );
        };

    It should_return_the_dashboard_page = () => 
        result.ShouldBeAView().And().ShouldUseDefaultView();
}

如果有人知识渊博的人可以否认,确认或以其他方式理解,那就太好了。

其他提示

在您的控制器动作中 return RedirectToAction 返回 RedirectToRouteResult 对象,不是 ViewResult, ,这就是它的抱怨。

为了将结果对象(在规格中)施加到 ViewResult 您的行动的返回声明必须看起来像:

 public ActionResult Index()
 {
     //Some code here

     return View(/*here maybe a model object*/);       
 }

为了修复测试,您只需要更改以下行:

It should_set_the_module_title = () => ((ViewResult)result ).ViewData[ "ModuleTitle" ].ShouldEqual("PM4 - Dashboard");

为此:

It should_set_the_module_title = () => ((RedirectToRouteResult)result).ViewData[ "ModuleTitle" ].ShouldEqual("PM4 - Dashboard");

希望这可以帮助。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top