2010-05-24 240 views
2

我试图测试/规格以下动作方法为什么此测试失败?

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,但为[空]

但我上午返回的东西 - 其实,一个RedirectToRouteResult - 在每个方式方法可以结束! MSpec为什么认为结果为null

+0

那么它有点儿时髦。那是什么测试框架? – Dann 2010-05-24 08:46:59

+0

@burnt_hand,'ThenIt'(正如问题中所述)只是Machine.Specifications(MSpec)中的It的别名,以避免与'Moq.It'冲突。 – 2010-05-24 08:55:47

回答

2

我找到了答案。取而代之的

Because of =() => controller.ChangePassword(inputModel); 

当然我需要

Because of =() => result = controller.ChangePassword(inputModel); 

因为没有设定值resultresult显然会null。叹。