'Y'

Testing Applications with JUnit5 and Mockito. Part 2

The second article in our series on EasyMock, JMock and Mockito. Happy reading.

Web client with Mockito 1.JPG

Web client with Mockito 2.JPG


In listing 7 we do the following:

  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.

Conclusions


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.



Catalin Tudose
Java and Web Technologies Expert

Share the knowledge

Still have questions?
Connect with us
Thank you.
Your request has been received.