Indexers allow objects to behave like arrays. Dictionary class in .NET, for example, provides an indexer that allows the retrieval of the item from the dictionary that corresponds to a particular key.
There are two ways you can go about mocking indexers defined on interfaces when using NMock.
-
You can use the Get property to describe what should be returned when a particular parameter is passed. The following expectations for example, cause “xxx” to be returned when foo[“aaa”] or foo[“bbb”] is called.
Expect.Once.On(foo).Get["aaa"].Will(Return.Value(“xxx”));
Expect.Once.On(foo).Get["bbb"].Will(Return.Value(“xxx”));This approach works fine in most circumstances. However you are required to provide all the values with which the indexer can be invoked. This presents a problem in the scenario where you need to return a particular value irrespective of the value of the input parameter.
-
Indexers are implemented under the hood as methods so NMock’s support for mocking methods can be used to mock indexers. An indexer definition is munged by the compiler to a pair of get_Item and set_Item methods. When you call foo[“aaa”], it is munged by the compiler to a call to the get_Item method on foo with “aaa” as the argument.
So here’s what you can do to make sure that “xxx” is returned irrespective of the value of the parameter passed to the indexer.
Stub.On(foo).Method(“get_Item”).Will(Return.Value(“xxx”));
Now any call of the form foo[<BLAH>] will return “xxx”.




