Last year, my colleague Ben introduced us to the joys of hand-rolling mocks. This allowed us to ignore interactions we weren’t worried about, leading to cleaner tests.
This year, I’m mocking again. I’ve mentioned it briefly before, but now that I’ve used Mockito a bit more, I really love it. Here’s a quick summary to show why.
public class GameBehaviour { @Test public void shouldApplyRulesToOriginalGridThenEachGeneratedGridInTurn() { // Given Rules rules = mock(Rules.class); Grid firstGrid = mock(Grid.class); Grid secondGrid = mock(Grid.class); Grid anyGrid = Grid.NULL; GridFactory factory = mock(GridFactory.class); stub(factory.createGrid(anyInt(), anyInt())).toReturn(firstGrid); stub(rules.applyTo(firstGrid)).toReturn(secondGrid); stub(rules.applyTo(secondGrid)).toReturn(anyGrid); // When Game game = new Game(5, 5, rules, factory); game.nextGeneration(); game.nextGeneration(); // Then verify(rules).applyTo(firstGrid); verify(rules).applyTo(secondGrid); } }
There are some quite complex factors in this Game of Life – infinite, bounded or wrapped grids, rules which could be Conway’s or the High Life rules, etc. – hence the design pattern overkill. Here’s something simpler:
public class GameFrameBehaviour { @Test public void shouldHaveAButtonForTheNextGeneration() throws Exception { // Given WindowControl windowWrapper = new WindowControl("game.frame"); Game game = mock(Game.class); new GameFrame(game); // When windowWrapper.clickButton("next.step"); // Then verify(game).nextGeneration(); } }
I leave it to you to work out what these look like with other mocking frameworks. You can look at Szczepan’s comparisons to get an idea.
Thanks, Szczepan.