Test Doubles, Mocks, and Matchers
This training covers Test Doubles, Mocks (using Mockito), and Hamcrest Matchers.
- 1 Prerequisites
- 2 Slide Deck
- 3 Section 1: Introduction to Test Doubles and Mockito
- 4 Section 2: Advanced Mockito - Argument Captors, Spies, and Annotations
- 5 Section 3: Hamcrest Matchers, Tips and Tricks
- Current release of the LDSTech IDE, or an IDE you are familiar with
- Java JDK 1.6+
- Unit Testing with TestNG
Section 1: Introduction to Test Doubles and Mockito
- Download the training project template
- Unzip the artifact where you typically keep training or other projects
- The mocks-training/mocks directory should be the root of your project. There a variety of ways to open this, depending on your IDE:
- For LDS Tech IDE, open the mocks-training folder as a workspace in your LDS Tech IDE, and then import mocks-training/mocks as the root directory.
- NOTE: there are three Maven modules in the project. Please import all three if you would like to see example code from the training. The work you will be doing for the labs is in the labs module.
- For this first lab, you will be configuring an existing test class to use Mockito. The class to modify is org.lds.stack.training.mocks.service.ContactServiceImplTest. I have provided the tests, the assertions, and the test fixtures. Complete the lab by adding the necessary mock features. All changes are marked with TODO comments.
- The first comment prompts you to initialize the contentRepository field as a mock. One way to do this would be the following code:
contactRepository = mock(ContactRepository.class);
- There is a total of eight items to modify in the class. Refer to the slide deck if you get stuck. Remember to run the tests to verify that they are actually working now.
Lab 1 Solution
Section 2: Advanced Mockito - Argument Captors, Spies, and Annotations
- For this lab, you will be modifying a clone of the test we worked on in the first lab to use the Mockito annotations that we discussed in section two of the training. Additionally, you will be modifying some of the tests to use argument captors. The class to modify is org.lds.stack.training.mocks.service.AnnotationContactServiceImplTest. As in the prior lab, all changes are marked with TODO comments.
- The first comment prompts you to add the appropriate Mockito annotations to each field. To apply this to contactRepository do the following:
@Mock ContactRepository contactRepository;
- NOTE: there appears to be a bug in how @InjectMocks is being processed. Continue to construct ContactServiceImpl the same way it is in the lab, but you can annotate all of the other fields.
- There are just six items to modify in this lab. Use the instructions, along with the partially-completed tests, to determine how best to create your expectations, verifications, and argument captors.
Lab 2 Solution
Section 3: Hamcrest Matchers, Tips and Tricks