Search code examples
c#.netunit-testingmockingnmock

Using Mock objects with Dictionary


I just started working with Unit Testing with NMock

I one my test cases involve adding an entry in a dictionary which is then passed to the unit being tested. I define the map as:

var item = new Mock<MyClass>().Object;
var myMap = new Dictionary<MyClass, IList<MyOtherClass>> 
             { 
                { item, completionRequirement }
             };

However when I do a myMap.ContainsKey(item) inside the unit being tested it returns false.

I am able to view a proxied item in the Dictionary on inspecting it. I am guessing that I need to do something else as well on the mocked item.(Most probably define .Equals(object o)).

My question is :

  • How do you define the Equals(object o) for the mocked item.
  • Or is there a different solution to the problem altogether.

Solution

  • You might want to mock the dictionary as well. That is, refactor to use IDictionary<MyClass,IList<MyOtherClass>, then pass in a mocked dictionary. You can then set up expectations so that it returns mocked objects as necessary.

    It's also possible that you may not need to use a mock at all in this instance. It's not possible to tell from what you've given us, but I've often found that people new to mocking can sometimes forget that you can use the real objects as well if those objects don't have cascading dependencies. For example, you don't really need to mock a class that's just a simple container. Create one and use it, instead. Just something to think about.