Search code examples
c#testingmockingmoq

Is it possible to pass-through parameter values in Moq?


I need to mock HttpResponseBase.ApplyAppPathModifier in such a way that the parameter ApplyAppPathModifier is called with is automatically returned by the mock.

I have the following code:

var httpResponseBase = new Mock<HttpResponseBase>();
httpResponseBase.Setup(hrb => hrb.ApplyAppPathModifier(/*capture this param*/))
                .Returns(/*return it here*/);

Any ideas?

EDIT:

Found a solution on the first page of Moq documentation (http://code.google.com/p/moq/wiki/QuickStart):

var httpResponseBase = new Mock<HttpResponseBase>();
httpResponseBase.Setup(hrb => hrb.ApplyAppPathModifier(It.IsAny<string>)
                .Returns((string value) => value);

I suddenly feel a lot stupider, but I guess this is what happens when you write code at 23:30


Solution

  • Use It:

    It.Is<MyClass>(mc=>mc == myValue)
    

    Here you can check the expectation: the value you expect to receive. In terms of return, just return value you need.

    var tempS = string.Empty;
    var httpResponseBase = new Mock<HttpResponseBase>();
    httpResponseBase.Setup(hrb => hrb.ApplyAppPathModifier(It.Is<String>(s=>{
               tempS = s;
               return s == "value I expect";
               })))
                    .Returns(tempS);