c# - 为什么这个测试失败了?

标签 c# asp.net-mvc-2 mspec

我正在尝试测试/指定以下操作方法

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);

由于没有将值设置为 resultresult 显然将为 null。叹息。

关于c# - 为什么这个测试失败了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2895201/

相关文章:

c# - SQLite 事务未提交

c# - 我怎样才能让我的 dapper 结果成为一个列表?

asp.net-mvc-2 - 需要帮助将 DefaultModelBinder 用于嵌套模型

caching - donut 缓存 ASP.NET MVC2

testing - 在 MSpec 中 stub 静态方法

c# - FromsAuthenticationTicket.UserData 始终为空并且身份验证 cookie 不保留值

c# - Publishesettings 告诉该位置是保留的系统名称或磁盘不可写?

c# - ASP.NET MVC 对象引用未设置为对象的实例

c# - 使用 MSpec 比较两个列表

mspec - 为什么缺少 MSpec 的 ShouldBeOfType<T> 断言扩展方法?