JUnit 5 Architecture. Part 3
JUnit 5 Architecture. Part 3
In this third part of our article series on JUnit 5 Architecture we look at rules vs the extension model. Happy reading.
12 May 2020
1272
Other articles
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
6. Rules vs the extension model
In order to put face-to-face the rules model of JUnit 4 and the extension model of JUnit 5, let’s use a Calculator class (listing 1). It’s used to execute mathematical operations, from verifying their systems under test. We are interested in testing the methods that may throw exceptions. One rule is ExpectedException. It can be easily replaced by the JUnit 5 assertThrows method.
The logic that may throw exceptions into the Calculator class does the following:
- Declares a method to calculate the square root of a number (1). In case the number is negative, an exception containing a particular message is created and thrown (2).
- Declares a method to divide two numbers (3). In case the second number is zero, an exception containing a particular message is created and thrown (4).
Listing 2 provides an example that specifies which exception message is expected during the execution of the test code using the new functionality of the Calculator class above.
Into the previous JUnit 4 example, we do the following:
- We declare an ExpectedException field annotated with @Rule. The @Rule annotation must be applied either on a public non-static field or on a public non-static method (1). The ExpectedException.none() factory method creates an unconfigured ExpectedException.
- We initialize an instance of the Calculator class whose functionality we’re testing (2).
- The ExpectedException is configured to keep the type of exception (3) and the message (4), before being thrown by invoking the sqrt method at line (5).
- The ExpectedException is configured to keep the type of exception (6) and the message (7), before being thrown by invoking the divide method at line (8).
Interested in Java? Check out our trainings.
Catalin Tudose
Java and Web Technologies Expert