Tôi muốn thiết lập một phương thức với Moq hai lần nhưng có vẻ như phương thức cuối cùng sẽ ghi đè các phương thức trước đó. Đây là thiết lập ban đầu của tôi:Làm thế nào để thiết lập một phương pháp hai lần cho các tham số khác nhau với giả
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
});
này hoạt động ra tốt đẹp nhưng tôi muốn điều này trở new ValidUserContext()
nếu tên người dùng hoặc mật khẩu không chứ không phải là username
và password
biến như trên. Để làm điều đó, tôi đã thêm thiết lập khác nhưng lần này nó ghi đè lên một ở trên và luôn áp dụng nó:
membershipServiceMock.Setup(ms =>
ms.ValidateUser(It.IsAny<string>(), It.IsAny<string>())
).Returns(
new ValidUserContext()
);
cách thanh lịch nhất của xử lý kiểu này tình huống với Moq là gì?
Sửa
tôi giải quyết vấn đề với cách tiếp cận dưới đây nhưng tôi đoán đó là một cách tốt hơn để xử lý này:
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()
);
Giải pháp đầu tiên không xử lý trường hợp khi u == tên người dùng và mật khẩu p! = Hoặc thực hiện? –