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.
有帮助吗?

解决方案

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.

其他提示

The approach given at http://richardashworth.blogspot.com/2011/12/using-reflection-to-create-mock-objects.html is in Java, but presents another approach to this problem using Reflection.

I like the idea of setting up a 'fake' object along the lines of what tvanfosson is suggesting.

But if you want to do it with a mocking framework, I think all you need to do is setup an expectation for what item.Object should be. In Rhino Mocks the syntax would be something like:

var knownObject = "myKey";
var mock = MockRepository.GenerateStub<IMyClass>();
mock.Stub(x=>x.Object).Return(knownObject);

That said, I have no idea what the equivalent code would be in NMocks, but it shouldn't be hard to figure it out if you're working with it (you can always ask a question on the user group).

HTH

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top