Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Moq to set any by any key and value

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

like image 628
Digicoder Avatar asked Jun 09 '11 14:06

Digicoder


1 Answers

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;
});
like image 162
Matthew Manela Avatar answered Sep 28 '22 03:09

Matthew Manela