Using Moq to set any by any key and value

Digicoder picture Digicoder · Jun 9, 2011 · Viewed 14.9k times · Source

At the end of the question: Using Moq to set indexers in C#, there was an issue that someone highlighted a problem that I am having as well. But they did not find a solution.

Specifically, I'm trying to use the generic It.IsAny<string> as the matcher for the key and setting the value via It.IsAny<object>. When accessing via an index and setting the value, it never matches and it does not access my call back method. And so my unit tests are failing.

var stateTable = new HashTable;
var httpSession = new Mock<HttpSessionStateBase>();

//works via httpSession.Add(key, value);
httpSession.Setup(x => x.Add(It.IsAny<string>(), It.IsAny<object>()))
    .Callback((string index, object value) => {
        var i = index;
        var v = value;

            stateData[i] = v;
    });

//does not work via httpSession[key] = value;
httpSession.SetupSet(x => x[It.IsAny<string>()] = It.IsAny<object>())
    .Callback( (string index, object value) => {
        var i = index;
        var v = value;

        stateData[i] = v;
});

I'm using Moq 4.0.10827

Answer

Matthew Manela picture Matthew Manela · Jun 9, 2011

In my experience this never works, you cannot use the It.IsAny as a matcher in the indexer expression. However, it will match if you put a concrete value in the indexer. For example, the following does work:

httpSession.SetupSet(x => x["someValue"] = It.IsAny<object>())
    .Callback( (string index, object value) => {
        var i = index;
        var v = value;

        stateData[i] = v;
});