In the third part of our article on JUnit we look at how we test with custom rules and extensions.
4. Testing with custom rules and extensions
We move our attention to replacing the custom rules. Using the own rules for the tests is particularly useful when some types of tests need similar additional actions before and after their execution.
For this demonstration, we have created our own classes which implement the TestRule
interface. To do this, one has to override the apply(Statement, Description)
method which returns an instance of Statement
. Such an object represents the tests within the JUnit runtime and Statement#evaluate()runs
them. The Description
object describes the individual test. We can use it to read information about the test through reflection.
Listing 6 The CustomRule class
To clearly show how to define our own rules, we look at listing 6, where we do the following:
- We declare our CustomRule class that implements the TestRule interface (1).
We keep references to a Statement field and to a Description field (2) and we use them into the apply method that returns a CustomStatement (3).
Listing 7 The CustomStatement class
In listing 7, we do the following:
- We declare our CustomStatement class that extends the Statement class (1).
We keep references to a Statement field and to a Description field (2) and we use them as arguments of the constructor (3).
We override the inherited evaluate method and call base.evaluate() inside it (4).
Interested in JUnit? Check out our trainings.
Java and Web Technologies Expert