我正在测试一个 MVC 控制器,并想测试在我的一个存储库中是否调用了 Save 方法。控制器是一个正在尝试注册用户的 AccountController。My AccountRepository 有两种方法,Save 和 Register。经过一些检查后,Register 正在调用 Save。我不确定我是否应该只测试 Register 是否被调用并在我的存储库上运行单独的单元测试以验证 Save 是否作为调用 Register 的一部分被调用,或者我是否在测试中错误地设置了 Moq。
这是我的测试:
[TestMethod]
public void register_post_saves_valid_registration()
{
_mockMemberRepository.Setup(r => r.GetByEmail(It.IsAny<string>())).Returns(_testMember);
// Arrange
RegisterViewModel model = new RegisterViewModel()
{
Email = "registerme@talentsite.com",
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
方法只接受一个 Member 对象并且是一个 void 方法。
我究竟做错了什么?