Introduction

Welcome to the Effective Unit Tests Series. The purpose of this series is to document some best practices for writing proper unit tests in your applications.

The tests in this series focus on using the following testing frameworks: JUnit, Mockito, Hamcrest. But you can swap these out for the equivalent frameworks that you use (e.g. JAssert instead of Hamcrest, etc.). The guidance documented here is general and should apply to all unit test setups.

Also, the test code contained within each item uses the BDDMockito approach to writing mock related code rather than the default Mockito approach but this is just my personal choice and it makes no difference which one you choose as they are completely equivalent.

e.g. This:

given(employeeNumberGenerator.generate(anyString())).willReturn("EUS1002");

is equivalent to this:

when(employeeNumberGenerator.generate(anyString())).thenReturn("EUS1002");

And this:

then(eventBroadcaster).should().broadcast(EventType.USER_REGISTRATION, mockSavedUserEntity);

Is equivalent to this:

verify(eventBroadcaster).broadcast(EventType.USER_REGISTRATION, mockSavedUserEntity);

All of the source code for this series can be found in https://github.com/partial-overflow/Effective-Unit-Tests/.