Testing Applications with JUnit5 and Mockito. Part 2
Testing Applications with JUnit5 and Mockito. Part 2
The second article in our series on EasyMock, JMock and Mockito. Happy reading.
2 лист 2020
2115
Інші статті
How to incrementally migrate the data from RDBMS to Hadoop using Sqoop Incremental Last Modified technique?
How to implement Slowly Changing Dimensions(SCD) Type 2 in Spark?
How to incrementally migrate the data from RDBMS to Hadoop using Sqoop Incremental Append technique?
Why MongoDB don't fetch all the matching documents for the query fired
How to solve the issue of full disk utilization in HDFS Namenode
Can We Use HDFS as Back-up Storage?
How to do Indexing in MongoDB with Elastic Search? Part 1
How to do Indexing in MongoDB with Elastic Search? Part 2
How to store data on browser using NoSQL IndexedDB?
How to Apply MBTI in HR: Motivation for every day. Groups of People & their Motivations
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.
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