4

For developers with extensive experience using mocks, is it okay to mock multiple objects in one class (ie satisfy multiple interfaces) or is this not recommended?

I am wondering because mocks are stubs anyway, from a testing perspective, it doesn't seem to make a big difference if I consolidate mocks.

However, I do wonder if there are negative impacts from a maintenance/clarity POV.

1

2 Answers 2

3

I can only think of a couple of situations where it might be a bad idea:

  1. If your unit tests are part of the documentation (e.g. for a shared API) then you don't want to set a bad example. If you expect that real implementations would implement more than one interface then you can/should ignore this.
  2. If your mock classes are anything more than simple stubs, then you risk making them unnecessarily complicated. Hopefully this falls under common sense!

With those exceptions, I don't see it being a problem.

0
2

Yes, it is perfectly fine.

One example I could think of is the MVP design pattern. If you pass model and view objects to the presenter with their interfaces, then you have to pass two mock objects in unit tests.

3
  • 2
    How is that example relevant? Yes, you would have to pass in View and Model references, but I don't see how that has any bearing on whether the objects are of 2 separate classes or of one class which implements both the View and Model interfaces... Commented Jan 8, 2013 at 13:48
  • 1
    @Baqueta The example shows that it is perfectly fine to pass more then one mocks to a class. That is the point of the question : is it okay to mock multiple objects in one class (ie satisfy multiple interfaces) or is this not recommended? Commented Jan 8, 2013 at 14:10
  • 1
    I think you've misunderstood the question. By "satisfy multiple interfaces" I think he means having a mock class like class MockViewModel implements View, Model { /* ... */ } Commented Jan 8, 2013 at 14:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.