对于我正在从事的项目,我正在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?

最佳答案

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

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

关于c# - 手动将RedirectToRouteResult解析为查看结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19141469/

10-12 00:01