简体   繁体   English

如何使用Moq传递List参数

[英]How to pass a List parameter using Moq

I am trying to mock a method which takes two parameters, the signature of method looks as follows: 我正在尝试模拟一个带有两个参数的方法,该方法的签名如下所示:

User DoSomething(User user, List<Role> newRoleList);

I want this method to return something only if the 'newRoleList' parameters contains some predefined roles and a specific username in it. 我希望此方法仅在'newRoleList'参数包含一些预定义角色和特定用户名的情况下返回某些内容。 So instead of using It.IsAny<> I'm trying to use It.Is<> . 因此,而不是使用It.IsAny<>我试图用It.Is<> The problem I am facing is with the 2nd parameter. 我面临的问题是第二个参数。 How can I setup this 2nd parameter? 如何设置第二个参数?

I'm trying to achive something like this: 我正在尝试达到这样的目标:

List<Role> roleList = new List<Role>()
    {
        new Role() { RoleName="RoleOne}, 
        new Role() { RoleName="RoleTwo"}
    };

mockComponent.Setup(x => x.UpdateUserRoles(
                            It.Is<User>(user1 => user1.UserName == "DummyUser"), 
                            It.Is<List<Role>>(y=>y==roleList)
                    ))
             .Returns(user);

But this is always returning 'null'. 但这总是返回“ null”。 If I change the 2nd parameter to It.IsAny<List<Role>>() then it's returning me a proper value. 如果我将第二个参数更改为It.IsAny<List<Role>>()那么它将为我返回一个适当的值。

Please suggest how to achieve this, is there any better way for supplying a specific list as parameter or what? 请建议如何实现,是否有更好的方法来提供特定列表作为参数或提供什么?

Finally I found the solution, I need to specify in my setup the criteria for how to treat two lists equal. 最后,我找到了解决方案,我需要在设置中指定如何将两个列表相等的标准。

I have changed the code to: 我已将代码更改为:

mockComponent.Setup(x => x.UpdateUserRoles(It.Is(user1 => user1.UserName == "DummyUser"),It.Is>(y=>y[0].RoleName=="RoleOne" && y[1].RoleName=="RoleTwo"))).Returns(user); mockComponent.Setup(x => x.UpdateUserRoles(It.Is(user1 => user1.UserName ==“ DummyUser”),It.Is>(y => y [0] .RoleName ==“ RoleOne” && y [ 1] .RoleName == “RoleTwo”)))返回(用户)。

It's working like a charm.. 它像魅力一样运作..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM