2010-05-24 183 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。嘆。