Testing Applications with JUnit5 and Mockito. Part 2

  1. We import the needed dependencies, static and non-static in this example (1).
  2. 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.
  3. 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.
  4. In (6) we call the method under test and in (7) we assert the expected result.
  5. 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.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store