Four mocks? One test? No problem!

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 {
    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);
        // When
        Game game = new Game(5, 5, rules, factory);
        // Then

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 {

    public void shouldHaveAButtonForTheNextGeneration() throws Exception {
        // Given
        WindowControl windowWrapper = new WindowControl("game.frame");
        Game game = mock(Game.class);
        new GameFrame(game);
        // When
        // Then

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.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s