我正在尝试测试/规范以下操作方法
public virtual ActionResult ChangePassword(ChangePasswordModel model)
{
if (ModelState.IsValid)
{
if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
{
return RedirectToAction(MVC.Account.Actions.ChangePasswordSuccess);
}
else
{
ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
}
}
// If we got this far, something failed, redisplay form
return RedirectToAction(MVC.Account.Actions.ChangePassword);
}
使用以下MSpec规范:
public class When_a_change_password_request_is_successful : with_a_change_password_input_model
{
Establish context = () =>
{
membershipService.Setup(s => s.ChangePassword(Param.IsAny<string>(), Param.IsAny<string>(), Param.IsAny<string>())).Returns(true);
controller.SetFakeControllerContext("POST");
};
Because of = () => controller.ChangePassword(inputModel);
ThenIt should_be_a_redirect_result = () => result.ShouldBeARedirectToRoute();
ThenIt should_redirect_to_success_page = () => result.ShouldBeARedirectToRoute().And().ShouldRedirectToAction<AccountController>(c => c.ChangePasswordSuccess());
}
其中with_a_change_password_input_model
是实例化输入模型的基类,为IMembershipService等设置模拟。第一个ThenIt
上的测试失败(这只是我用来的别名避免与Moq冲突...),并带有以下错误描述:
Machine.Specifications.SpecificationException:应该是System.RuntimeType类型但是[null]
但我我返回一些东西 - 实际上是一个RedirectToRouteResult
- 每种方法都可以终止!为什么MSpec认为结果为null
?
答案 0 :(得分:2)
我找到了答案。而不是
Because of = () => controller.ChangePassword(inputModel);
我当然需要
Because of = () => result = controller.ChangePassword(inputModel);
由于未将值设置为result
,result
显然为null
。叹息。