Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot implement setters (Moq)

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.

like image 834
Roman Bats Avatar asked Feb 25 '26 18:02

Roman Bats


1 Answers

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.

like image 199
Pablo Romeo Avatar answered Feb 27 '26 06:02

Pablo Romeo