Category Archives: TDD

Mocks/Stubs Difference

Mocks/Stubs

Whilst all of the other types of Test Double build on each other, gradually adding more functionality, Mocks are something totally different. Until now, all of our test doubles have made assertions on state. Mocks are test doubles that make assertions on behaviour. Mocks say “I expect you to call foo() withbar, and if you don’t there’s an error”.

Typically, using a Mock will consist of three phases:

  1. Creating the instance
  2. Defining the behaviour
  3. Asserting the calls

Taking our Stub example from above, we could turn that into a Mock like so:

public class FooCollectionTest
{
    @Test
    public void it_should_return_joined_bars()
    {
        Foo fooMock = mock(Foo.class); // instance
        when(fooMock.bar()).thenReturn("baz", "qux"); // behaviour

        FooCollection sut = new FooCollection();
        sut.add(fooMock);
        sut.add(fooMock);

        assertEquals("bazqux", sut.joined());
        verify(fooMock, times(2)).bar(); // verify
    }
}

If we left out the call to verify(), the above example is still a Stub, even though it’s using a mocking framework. The difference here is so subtle it’s no wonder it leads to confusion. fooMock doesn’t become a Mock until we call verify at the end, as that’s the key differentiator between a Mock and the other types of Test Doubles.

With the Stub we only assert on the state of the object, but with the Mock we assert that the correct methods were called the correct number of times (and sometimes in the correct order and with the correct parameters).