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

前端 未结 3 911
慢半拍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:13

    Moq supports this out of box with argument constraints:

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

    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(), It.IsAny())
        .Returns(new ValidUserContext());
    mock.Setup(ms => ms.ValidateUser(
            It.Is(u => u == username), It.Is(p => p == password))
        .Returns(new ValidUserContext { Principal = principal });
    

提交回复
热议问题