Testing Applications with JUnit5 and JMock. Part 1
1. Using JMock
This far we saw how to implement our own mock-objects and how to use the EasyMock framework. In this section we introduce the JMock framework (http://jmock.org/), to get the full view on the different mocking techniques. We’ll follow the same scenario t: testing money transfer with the help of a mock AccountManager, this time using JMock.
In order to work with JMock, we need to add to the pom.xml file the dependencies from listing 1:
Listing 2 presents a very simple Account object with two properties: an account ID and a balance.
Listing 3 shows the AccountManager interface that manages the life cycle and persistence of Account objects (limited to finding accounts by ID and updating accounts):
Listing 4 shows the shows the transfer method designed for transferring money between two accounts. It uses the previously defined AccountManager interface to find the debit and credit accounts by ID and to update them.
We want to be able to unit test the AccountService.transfer behavior. For that purpose, until the implementation of the AccountManager interface is ready, we will use a mock implementation of the AccountManager interface because the transfer method is using this interface, and we need to test it in isolation.
Interested in JUnit? Check out our trainings.
Java and Web Technologies Expert