我正在尝试测试/指定以下操作方法
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: Should be of type System.RuntimeType but is [null]
但我正在返回一些东西——事实上,一个RedirectToRouteResult
——方法可以以各种方式终止!为什么 MSpec 认为结果为 null
?
最佳答案
我找到了答案。而不是
Because of = () => controller.ChangePassword(inputModel);
我当然需要
Because of = () => result = controller.ChangePassword(inputModel);
由于没有将值设置为 result
,result
显然将为 null
。叹息。
关于c# - 为什么这个测试失败了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2895201/