Don’t mock the class you’re testing

I first heard this rule in feedback on my Tic Tac Toe code challenge. It makes a lot of sense: if you’re trying to assess the behavior of a component, mocking it is no way to get a reliable test. If this is so obvious, why was I doing it? I find I tend to do this when the behavior I’m actually testing is that of a higher level object. Here’s a small example:

My Battleship game has a Game class, which is instantiated with a UI class. Early in the UI-building process, I wanted to write code to tell the UI to print the board on the start of each player turn. I’d already tested the printer, so it wasn’t the actual output I wanted to test, just the method. I found myself writing something like this:

public class UiTest {
public void receivesBoardPrintCallOnPLayerTurn() {
Ui mockUi = mock(Ui.class);

Pretty obviously, I’m not actually testing the UI here, but the Game. In Tic Tac Toe as well, I found that if I was mocking the object in its own test, I should think about what I’m actually trying to test and think about moving the test up an abstraction level.

I moved the test of game.playerTurn() on the Ui to GameTest, where mocking the Ui is allowed. I then wrote a Ui test to make sure it was properly passing the print command along to its printer.

(Side note: Mockito is my new favorite thing! It makes something that always felt a bit semantically awkward in rspec (mocking and stubbing) and makes it really simple and elegant 😀 .)

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.