How to set up a method twice for different parameters with Moq

前端 未结 3 908
慢半拍i
慢半拍i 2021-02-04 23:39

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\";
s         


        
3条回答
  •  长发绾君心
    2021-02-05 00:14

    If you look at the function definition for Setup():

    // Remarks:
    //     If more than one setup is specified for the same method or property, the latest
    //     one wins and is the one that will be executed.
    public ISetup Setup(Expression> expression);
    

    All you need to do is switch the order of the two Setup() calls:

    membershipServiceMock.Setup(ms =>
        ms.ValidateUser(It.IsAny(), It.IsAny())
    ).Returns(
        new ValidUserContext()
    );
    membershipServiceMock.Setup(ms =>
        ms.ValidateUser(username, password)
    ).Returns(new ValidUserContext { 
        Principal = principal
    });
    

    so if the input is indeed username and password, both Setup() calls are qualified but the later one wins because of the rule and when you have any other inputs, only the first one is matched and applied.

提交回复
热议问题