Javatpoint Logo
Javatpoint Logo

JUnit Rules

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:

  • Create directories/files that are deleted after a test method has been run.
  • Fail a test, if the described timeout has exceeded before a test method is invoked.
  • Establish an external resource like a socket or a database connection before a test method is invoked.
  • Free the configured external resource after a test method is invoked.

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.

ToDoService.java

Step 2: Create an implementation class named ToDoBusiness.

ToDoBusiness.java

Step 3: Create a test class named ToDoBusinessMock in which business logic is defined.

ToDoBusinessMock.java

Output

The following output shows that the test is successfully running using the JUnit rule (MockitoRule).

JUnit Rules
Next TopicPowerMock





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA