我再次遇到moq的问题而且不确定这次我做错了什么。
所以我逐步完成调试器,我注意到即使在我的模拟中我设置了
ResetPassword返回“嘿似乎没有
以下是我的单元测试的一部分:
var membershipMock = new Mock<MembershipProvider>();
var user = new Mock<MembershipUser>();
user.SetupGet(x => x.Email).Returns("Email");
user.Setup(x => x.ResetPassword("test")).Returns("hey");
membershipMock.Setup(m => m.GetUser("chobo2", false)).Returns(user.Object);
authentication.Authenticate.Provider = membershipMock.Object;
// Act
var actual = authentication.PasswordRecoveryStep2("chobo2","2z");
我的代码
MembershipUser userName = Provider.GetUser(user, false);
string newPassword = userName.ResetPassword(securityAnswer);
Mail.To = userName.Email;
Provider是一个使用模型对象设置的属性,如您所见。电子邮件部分填写正常。只是ResetPassword不会返回它应该的内容。它只是给我null。
由于
答案 0 :(得分:7)
如果“2z”是您的安全答案,Moq将不会返回“hey”,因为它的设置仅返回“hey”表示匹配“test”的字符串输入。以下对我来说非常适合:
public class AuthenticationHelper {
readonly MembershipProvider _provider;
public AuthenticationHelper(MembershipProvider provider) {
_provider = provider;
}
public string PasswordRecoveryStep2(string userName, string recoveryAnswer) {
MembershipUser user = _provider.GetUser(userName, false);
string newPassword = user.ResetPassword(recoveryAnswer);
return newPassword;
}
}
通过以下测试...
[TestFixture]
public class AuthHelperTests {
Mock<MembershipProvider> memberShipProvider;
Mock<MembershipUser> user;
[SetUp]
public void Init() {
memberShipProvider = new Mock<MembershipProvider>();
user = new Mock<MembershipUser>();
user.SetupGet(u => u.Email)
.Returns("test@test.com");
user.Setup(u => u.ResetPassword("secret"))
.Returns("test2");
memberShipProvider
.Setup(prov => prov.GetUser("test", false))
.Returns(user.Object);
}
[Test]
public void WillResetPasswordByCallingProvider() {
var helper = new AuthenticationHelper(memberShipProvider.Object);
string newPassword = helper.PasswordRecoveryStep2("test", "secret");
Assert.AreEqual("test2", newPassword);
memberShipProvider.Verify(p => p.GetUser("test", false));
user.Verify(u => u.ResetPassword("secret"));
}
}