Skip to main content

Section 11.4 To mock or not to mock

A natural question is: should you use mocks heavily, or lightly? Are there cases you are definitely better off mocking? Are there cases you are definitely better off not mocking? Let’s consider some tradeoffs:
  • Mocking allows the test to isolate more on specific behavior. A test that uses mocks is not likely to break for the wrong reasons. Our test above for example is not going to break because the GradeReader class isn’t implemented correctly, or because the Grade class isn’t implemented correctly.
  • In a test with mocks the interactions between classes are not being tested. The very nature of mocking the classes your class interacts with means that your tests do not do anything to test the interactions between the classes. On the one hand that’s a good thing, to have isolated unit tests, on the other hand though it means that those interactions need to be tested somewhere else, if you want your software to have any chance of working out in the real world.
Some general advice on when to mock and not to mock:
  • Mock on the boundaries between separate components of your application. When you are about to, for example, switch from the core of your application to the UI, that’s a good place to mock: You don’t want your tests to rely on something showing up on the screen, you simply want to test that your method attempted to put something on the screen, and a mock does that just fine.
  • Mock when you want to specify that a certain object calls another object in a very prescribed way. This is in effect what we did with the GradeReader and Summary classes, We wanted to make sure the Summary class called the GradeReader in a very precise manner. If you need to know if a function is being called, you need to spy on that function.
  • Don’t mock components too logically close to the component under test. If your object can’t really live without the particular implementation provided by some other objects, then perhaps the two should not be separated.
  • Most other cases are less clear, and they depend on more the school of thought you espouse.