gpt4 book ai didi

c# - 如何使用 Moq 为不同的参数设置方法两次

转载 作者:IT王子 更新时间:2023-10-29 04:00:02 26 4
gpt4 key购买 nike

我想用 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
});

这很好,但如果用户名或密码与 usernamepassword 不同,我希望它返回 new ValidUserContext()变量如上。为此,我添加了另一个设置,但这次它覆盖了上面的设置并始终应用它:

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()
);

最佳答案

Moq 支持带有参数约束的开箱即用:

mock.Setup(ms => ms.ValidateUser(
It.Is<string>(u => u == username), It.Is<string>(p => p == password))
.Returns(new ValidUserContext { Principal = principal });
mock.Setup(ms => ms.ValidateUser(
It.Is<string>(u => u != username), It.Is<string>(p => p != password))
.Returns(new ValidUserContext());

Catch-all It.IsAny 也可以,但顺序很重要:

// general constraint first so that it doesn't overwrite more specific ones
mock.Setup(ms => ms.ValidateUser(
It.IsAny<string>(), It.IsAny<string>())
.Returns(new ValidUserContext());
mock.Setup(ms => ms.ValidateUser(
It.Is<string>(u => u == username), It.Is<string>(p => p == password))
.Returns(new ValidUserContext { Principal = principal });

关于c# - 如何使用 Moq 为不同的参数设置方法两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12871897/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com