Testing Applications with JUnit5 and JMock. Part 1

Testing Applications with JUnit5 and JMock. Part 1

There are a lot of good projects already written to help us facilitate the usage of mock objects in our Java projects. In this series of articles, we take a closer look on three of the most widely-used mock frameworks: EasyMock, JMock and Mockito. We continue the series with JMock.

 

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 1 JMock Maven dependencies 1.JPG

 

Listing 2 presents a very simple Account object with two properties: an account ID and a balance.

The Account class 2.JPG

 

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):

AccountManager interface 3.JPG

 

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.

AccountService class 4.JPG

Interested in JUnit?

Check out our trainings

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. 

Tudose, Florin-Catalin , Java Champion; Java Chapter Lead; Author at Pluralsight and Manning

Tudose, Florin-Catalin Tudose author linkedin

Java Champion; Java Chapter Lead; Author at Pluralsight and Manning

Tudose, Florin-Catalin , Java Champion; Java Chapter Lead; Author at Pluralsight and Manning

Tudose, Florin-Catalin Tudose author linkedin

Java Champion; Java Chapter Lead; Author at Pluralsight and Manning