我正在測試一個MVC控制器,並且想要測試在我的某個庫中調用Save方法。控制器是一個正在嘗試註冊用戶的AccountController。我的AccountRepository有兩種方法,保存和註冊。一些檢查後,註冊正在調用保存。我不確定是否應該測試Register是否被調用,並在我的Repository上運行單獨的單元測試,以驗證Save是否作爲調用Register的一部分被調用,或者是否在我的測試中錯誤地設置了Moq。使用moq來驗證在mvc控制器上調用的方法
這裏是我的測試:
[TestMethod]
public void register_post_saves_valid_registration()
{
_mockMemberRepository.Setup(r => r.GetByEmail(It.IsAny<string>())).Returns(_testMember);
// Arrange
RegisterViewModel model = new RegisterViewModel()
{
Email = "[email protected]",
Password = "test123",
ConfirmPassword = "test123"
};
// Act
ActionResult result = _controller.Register(model);
// Assert
_mockMemberRepository.Verify(r => r.Register(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once());
_mockMemberRepository.Verify(r => r.Save(It.IsAny<Member>()), Times.Once());
}
這條線:
_mockMemberRepository.Verify(r => r.Register(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once());
通過了測試,但是當我介紹下面的一行:
_mockMemberRepository.Verify(r => r.Save(It.IsAny<Member>()), Times.Once());
失敗。
這裏是我的倉庫我的註冊方法:
public MembershipCreateStatus Register(string email, string password, string confirm)
{
if (password.Equals(confirm))
{
try
{
Member m = GetByEmail(email);
if (m == null)
{
int format = (int)PasswordFormatEnum.Encrypted;
string salt = GenerateSalt();
string pass = EncodePassword(password, format, salt);
m = new Member()
{
Email = email,
Password = pass,
PasswordSalt = salt,
PasswordFormat = format
};
Save(m);
return MembershipCreateStatus.Success;
}
else
return MembershipCreateStatus.DuplicateEmail;
//"A user with that email address already exists. Please use the Forgotten Password link if you need to recover your password.";
}
catch (Exception ex)
{
_logger.LogError(ex);
return MembershipCreateStatus.ProviderError;
}
}
return MembershipCreateStatus.InvalidPassword;
}
我Save
方法只需要一個成員對象,是一種無效的方法。
我在做什麼錯?
順便說一句,我回來時,它失敗的錯誤是'沒有設置配置。'。 – lloydphillips