对于我正在进行的项目,我正在 SpecFlow 1.9.2 中实现一些功能测试。
我在这些测试中遇到的问题是,我在尝试将 ActionResult 转换为 ViewResult 时遇到空引用异常。但是,存在此问题的原因是因为在我们的控制器中,我们有两个代码路径,如下所示:
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 异常。
为了试图规避这个问题,我尝试将RedirectToAction
HTTP 帖子中的调用更改为直接调用 on SomeOtherAction
,但这会导致站点错误。
问题:如上所述,我的问题的核心是 RedirectToRouteResult 不是 ViewResult。在功能测试的上下文中,有哪些方法可以解析 RedirectToRouteResult 以使控制器生成适当的 ViewResult?