سؤال

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. So instead of using It.IsAny<> I'm trying to use 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'. If I change the 2nd parameter to It.IsAny<List<Role>>() then it's returning me a proper value.

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<User>(user1 => user1.UserName == "DummyUser"),
              It.Is<List<Role>>(y=>y[0].RoleName=="RoleOne" && y[1].RoleName=="RoleTwo")))
           .Returns(user);

It's working like a charm..

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top