我想用 Moq 设置一个方法两次,但似乎最后一个覆盖了以前的。这是我的初始设置:
string username = "foo";
string password = "bar";
var principal = new GenericPrincipal(
new GenericIdentity(username),
new[] { "Admin" });
var membershipServiceMock = new Mock<IMembershipService>();
membershipServiceMock.Setup(ms =>
ms.ValidateUser(username, password)
).Returns(new ValidUserContext {
Principal = principal
});
这很好,但new ValidUserContext()
如果用户名或密码与上面的username
andpassword
变量不同,我希望它返回。为此,我添加了另一个设置,但这次它覆盖了上面的设置并始终应用它:
membershipServiceMock.Setup(ms =>
ms.ValidateUser(It.IsAny<string>(), It.IsAny<string>())
).Returns(
new ValidUserContext()
);
用 Moq 处理这种情况的最优雅的方法是什么?
编辑
我用下面的方法解决了这个问题,但我想有更好的方法来处理这个问题:
var membershipServiceMock = new Mock<IMembershipService>();
membershipServiceMock.Setup(ms =>
ms.ValidateUser(It.IsAny<string>(), It.IsAny<string>())
).Returns<string, string>((u, p) =>
(u == username && p == password) ?
new ValidUserContext {
Principal = principal
}
: new ValidUserContext()
);