如何使用Moq为不同的参数设置两次方法 [英] How to set up a method twice for different parameters with Moq

查看:124
本文介绍了如何使用Moq为不同的参数设置两次方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用Moq设置两次方法,但是似乎最后一个方法会覆盖以前的方法.这是我的初始设置:

I would like to set up a method with Moq twice but it seems that the last one overrides the previous ones. Here's my initial setup:

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().为此,我添加了另一个设置,但是这次它覆盖了上面的设置并始终应用它:

This works out fine but I want this to return new ValidUserContext() if the username or password is different to the username and password variables as above. To do that, I added another setup but this time it overrides the above one and always applies it:

membershipServiceMock.Setup(ms =>
    ms.ValidateUser(It.IsAny<string>(), It.IsAny<string>())
).Returns(
    new ValidUserContext()
);

用Moq处理这种情况的最优雅的方法是什么?

What is the most elegant way of handling this type of situation with Moq?

修改

我通过以下方法解决了问题,但我想有一种更好的方法来解决这个问题:

I solved the problem with the below approach but I guess there is a better way of handling this:

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通过参数约束对此进行了开箱即用:

Moq supports this out of box with argument constraints:

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

包罗万象 It.IsAny也可以,但是顺序很重要:

Catch-all It.IsAny also works, but the order is important:

// 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 });

这篇关于如何使用Moq为不同的参数设置两次方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆