手动将RedirectToRouteResult解析为视图结果

时间:2013-10-02 16:04:28

标签: c# unit-testing asp.net-mvc-4 redirect

对于我正在进行的项目,我正在SpecFlow 1.9.2中实现一些功能测试。

我遇到这些测试的问题是,在尝试将ActionResult强制转换为ViewResult时,我得到一个Null Reference异常。然而,这个问题存在的原因是因为在我们的控制器中,我们有两个代码路径,如:

public class CurrentController : Controller
{
    [HttpPost]
    public ActionResult SomeAction(MyModel model)
    {
        if(ModelState.IsValid)
        {
            model.Save();
            return RedirectToAction("SomeOtherAction", "Current");
        }

        // Views will be omitted as they're irrelevant to my question.
        return View(model);
    }

    [HttpGet]
    public ActionResult SomeOtherAction()
    {
        SomeModel model = new SomeModel();
        return View(model);
    }
}

...在我的功能测试中,我有一个步骤来调用HTTP帖子:

public class MyFeatureTest
{
    private ActionResult _actionResult;
    private ViewResult _viewResult;

    private MyModel _myModel;
    private SomeModel _someModel;

    // SNIP: Other steps unnecessary to this problem description...

    [When(@"I click save on the first action")]
    public void WhenIClickSaveOnTheFirstAction()
    {
        _actionResult = _currentController.SomeAction(_myModel);
        _viewResult = _actionResult as ViewResult;  // Evaluates to null
        _someModel = _viewResult.ViewData.Model as SomeModel;
    }
}

尝试分配_someModel时,抛出NullReference异常。

要尝试规避此问题,我尝试将HTTP帖子中的RedirectToAction电话更改为SomeOtherAction上的直接电话,但这会导致网站错误。

问题:如上所述,我的问题的核心是RedirectToRouteResult不是ViewResult。在功能测试的上下文中,有什么方法可以解析RedirectToRouteResult以使控制器生成适当的ViewResult?

1 个答案:

答案 0 :(得分:2)

默认情况下,ModelState.IsValid将返回true,这会导致RedirectToRouteResult而不是继续并返回ViewResult。

您可以尝试调用_currentController.ModelState.AddModelError()强制ModelState.IsValid返回false。