Arnold Zokas
Arnold Zokas

Reputation: 8590

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

Upvotes: 33

Views: 13869

Answers (3)

tridy
tridy

Reputation: 1284

If you are looking for mocking indexing properties and passing the key to a special "case" method that should be called, for example with IConfiguration that uses indexed properties, it can be done like this:

private IConfiguration GetConfigurationMock()
{
    var mock = new Mock<IConfiguration>(MockBehavior.Strict);
    mock.Setup(c => c[It.IsAny<string>()]).Returns((string key) => GetConfigValue(key));
    return mock.Object;
}

private string GetConfigValue(string key)
{
    return key switch
    {
        "MyKey" => "MyValue",
        _ => throw new NotSupportedException($"{key} is not supported."),
    };
}

Upvotes: 0

Russ Cam
Russ Cam

Reputation: 125538

Yes, you can echo back the argument passed to the method

httpResponseBase.Setup(x => x.ApplyAppPathModifier(It.IsAny<string>()))
                .Returns((string path) => path);

You can also capture it if you want

string capturedModifier = null;

httpResponseBase.Setup(x => x.ApplyAppPathModifier(It.IsAny<string>()))
                .Callback((string path) => capturedModifier = path);

Upvotes: 37

Aliostad
Aliostad

Reputation: 81700

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);

Upvotes: 13

Related Questions