The second article in our series on EasyMock, JMock and Mockito. Happy reading.
In listing 7 we do the following:
- We import the needed dependencies, static and non-static in this example (1).
- We extend this test using MockitoExtension (2). For this Mockito example, this extension is needed in order to be able to create the mock objects through annotations, as we do at (3). This tells Mockito to create one mock object of type ConnectionFactory and one mock object of type InputStream.
- In (4) we start the declaration of the expectations. Notice the fine way we declare the consecutive execution of the read() method of the stream (5), and also the returned values.
- In (6) we call the method under test and in (7) we assert the expected result.
- We also provide another @Test method, which tests our WebClient under exceptional conditions. In (8) we declare the expectation of the factory.getData() method, and in (9) we declare the expectation of the mockStream.read() method. In (10) we instruct Mockito to raise an IOException when we close the stream.
This article has demonstrated the steps needed to test a Java application with the help of JUnit 5 and Mockito. We showed how to test the functionality of an AccountService by mocking an AccountManager and of a WebClient by mocking a ConnectionFactory and an InputStream.
As you can see, the Mockito framework may be used with the new JUnit 5 extension model — and not programmatically, as JMock, but through the use of the JUnit 5 @ExtendWith and of the Mockito @Mock annotation.
Interested in JUnit? Check out our trainings.
Java and Web Technologies Expert
Originally published at https://www.luxoft-training.com.