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

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

    Another out-of-the-box option is to use the Return<> version to return different ValidUserContexts depending upon the parameters. It is not better than the above answer, just another option.

    We set up ValidateUser() to return the result of a function GetUserContext(string, string), passing in the username and password with which ValidateUser() was called.

    [TestClass]
    public class MultipleReturnValues {
    
        public class ValidUserContext {
            public string Principal { get; set; }
        }
    
        public interface IMembershipService {
            ValidUserContext ValidateUser(string name, string password);
        }
    
        [TestMethod]
        public void DifferentPricipals() {
    
            var mock = new Mock();
            mock.Setup(mk => mk.ValidateUser(It.IsAny(), It.IsAny())).Returns(GetUserContext);
    
            var validUserContext = mock.Object.ValidateUser("abc", "cde");
    
            Assert.IsNull(validUserContext.Principal);
    
    
            validUserContext = mock.Object.ValidateUser("foo", "bar");
    
            Assert.AreEqual(sPrincipal, validUserContext.Principal);
    
    
        }
    
        private static string sPrincipal = "A Principal";
        private static ValidUserContext GetUserContext(string name, string password) {
    
            var ret = new ValidUserContext();
    
            if (name == "foo" && password == "bar") {
                ret = new ValidUserContext { Principal = sPrincipal };
            }
            return ret;
    
        }
    }
    

提交回复
热议问题