Watch the Lesson

What Is a JUnit 4 Rule?

A JUnit 4 rule is a component that intercepts test method calls and allows us to do something before a test method is run and after a test method has been run. All JUnit 4 rule classes must implement the org.junit.rules.TestRule interface.

We can do pretty cool stuff with JUnit 4 rules. For example, JUnit 4 provides rules that can:

Create files and directories which are deleted after a test method has been run.

Fail a test if the specified timeout is exceeded before a test method has been run.

Configure an external resource such as a socket or a database connection before a test method is run and free the external resource after a test method has been run.

Next, we will find out how we can use JUnit 4 rules in our test classes.

Using Junit 4 Rules

We can use JUnit 4 rules by following these steps:

Add a public field to our test class and ensure that the type of this field is a subtype of TestRule.

Annotate the field with the @Rule annotation.

JUnit 4 requires that rule fields are public, aren’t static, and are a subtype of TestRule.

Let’s assume that we want to use the FooBarRule in our test class. After we have enabled this rule, the source code of our test class looks as follows:

Let’s use this information and find out how we can create files and directories which are deleted after a test method has been run.

Using the TemporaryFolder Rule

If we have to create files and/or directories which are deleted after a test method has been run, we have to use the TemporaryFolder rule. As we remember, if we want to enable this rule, we have to add a public TemporaryFolder field to our test class and annotate that field with the @Rule annotation.

After we have enabled the TemporaryFolder rule, the source code of our test class looks as follows:

The TemporaryFolder rule doesn’t ensure that the created files and directories were deleted successfully. If we are using JUnit 4.13 or newer, we can configure the TemporaryFolder rule to throw an AssertionError if the created files and directories cannot be deleted.

If we want to enable this feature, we have to create the TemporaryFolder object by using the following code: