3

I have next interface

    public interface IMyInterface
{
    string this[string key] { get; set; }
}

and i want implement get/set in my test

var _Nvp = //...
var mockMyInterface = new Mock<IMyInterface>();
        mockMyInterface
            .Setup(e => e[It.IsAny<string>()])
            .Returns((string key) => _Nvp[key]);

        mockMyInterface
            .SetupSet(c => c[It.IsAny<string>()] = It.IsAny<string>())
            .Callback((string key, string value) => { _Nvp[key] = value; }));

But it does not work.. No errors, no messages..

        var oj = mockMyInterface.Object;
        oj["key"] = "value";
        var value = oj["key"];

Variable value is always null.

Roman Bats
  • 1,775
  • 3
  • 30
  • 40

1 Answers1

4

Check out the following SO comment.

It seems there is a limitation on Moq's side resolving c[It.IsAny<string>()] on the SetupSet. It seems to work when specific keys are specified.

In your case you might want to go with a Stub with internal state implementing your interface rather than a mock.

Community
  • 1
  • 1
Pablo Romeo
  • 11,298
  • 2
  • 30
  • 58