Search code examples
c#tddmockingmoq

How to MOQ an Indexed property


I am attempting to mock a call to an indexed property. I.e. I would like to moq the following:

object result = myDictionaryCollection["SomeKeyValue"];

and also the setter value

myDictionaryCollection["SomeKeyValue"] = myNewValue;

I am doing this because I need to mock the functionality of a class my app uses.

Does anyone know how to do this with MOQ? I've tried variations on the following:

Dictionary<string, object> MyContainer = new Dictionary<string, object>();
mock.ExpectGet<object>( p => p[It.IsAny<string>()]).Returns(MyContainer[(string s)]);

But that doesn't compile.

Is what I am trying to achieve possible with MOQ, does anyone have any examples of how I can do this?


Solution

  • It appears that what I was attempting to do with MOQ is not possible.

    Essentially I was attempting to MOQ a HTTPSession type object, where the key of the item being set to the index could only be determined at runtime. Access to the indexed property needed to return the value which was previously set. This works for integer based indexes, but string based indexes do not work.