In the above examples, we have used the JUnit runner (MockitoJUnitRunner). It makes the test dependent on that particular runner.
We cannot use multiple runners in the same test. To overcome this problem, we should follow JUnit rules that makes the test more flexible. It allows us to use multiple rules in the same test.
A JUnit rule is defined as a component that is used to obstruct the test method calls and allows us to perform something before and after the test method is invoked. The JUnit provides the following rules to:
To use the JUnit rules, we need to add the @Rule annotation in the test.
@Rule: It annotates the fields. It refer to the rules or methods that returns a rule. The annotated fields must be public, non-static, and subtypes of the TestRule or MethodRule.
In the above code snippet, we have used the MockitoRule class. You can use any JUnit rule as per your requirement.
Example of JUnit Rule (MockitoRule)
Here, we are going to create an example using the JUnit rule. In this example, we are using the MockitoRule, and we can use any JUnit rule as per your requirement.
Step 1: Create an interface named ToDoService that contains two unimplemented methods.
Step 2: Create an implementation class named ToDoBusiness.
Step 3: Create a test class named ToDoBusinessMock in which business logic is defined.
The following output shows that the test is successfully running using the JUnit rule (MockitoRule).