understanding JUnit Rule

Junit Rules are used to add extra functionality that can applied to all test methods in a test class. Rules can be used as an alternative to @Before/@After and @BeforeClass/@AfterClass.

Junit Rule works on the principle of AOP framework; it intercepts the test method calls and provides an opportunity to do some useful stuff before and after method execution.


Predefined Junit Rules

Junit provides some out-of-box helper classes that can be used as rules with our test class. Let's take an example of TemporayFolder helper class provided by Junit to understand rules better.

public class JunitRuleTest {

  @Rule
  public TemporaryFolder tempFolder = new TemporaryFolder();

  @Test
  public void testRule() throws IOException {
    File newFolder = tempFolder.newFolder("Temp Folder");
    assertTrue(newFolder.exists());
  }
} 

On executing the above test class, the TemporayFolder rule will create a temporary folder named 'Temp Folder'. This folder is automatically deleted after the execution of the test method.


Testing Exception with Junit Rules

Junit rule provides a convenient way for testing exception conditions. The ExpectedException helper below shows how to use JUnit Rule for exception testing.

public class JunitExceptionRuleTest {

  @Rule
  public ExpectedException exception = ExpectedException.none();

  @Test
  public void testExceptionRule(){
      exception.expect(ArithmeticException.class);
      Calculator calc = new Calculator();
      calc.divide(20, 0);
  }
}

In the example above we define an ExpectedException rule, which says no exception should be thrown (ExpectedException.none()). If any test method throws some kind of an Exception, it would be marked as failed. However, with testExceptionRule() we explicitly specify that we are expecting an ArithmeticException. So, this method will be marked as successful only if it throws an ArithmeticException.


Creating Custom Rule

To create a custom rule, we need to implement the TestRule interface. TestRule defines a method as shown below:

public Statement apply(Statement stmt, Description desc).

The method has a Statement object and a Description object as its parameter. The statement represents a Junit test method which is used to run the test method. The description object provides information about the Junit test by applying java reflection.

The example below demonstrates how to create a Junit Rule.

public class HelloWorldRule implements TestRule{

    @Override
    public Statement apply(Statement stmt, Description desc) {

        return new Statement() {
			
	    @Override
	    public void evaluate() throws Throwable {
	        System.out.println("Before executing method "+ desc.getMethodName());
	        stmt.evaluate();
	        System.out.println("After executing method "+ desc.getMethodName());
	    }
        };
    }
}
public class HelloWorldRuleTest {
	
    @Rule
    public HelloWorldRule rule = new HelloWorldRule();
	
    @Test
    public void testHelloWorldRule(){
        System.out.println("Inside testHelloWorldRule");
    }
}

The HelloWorldRuleTest above would generate the following output on console:

Before executing method testHelloWorldRule
Inside testHelloWorldRule
After executing method testHelloWorldRule

As we stated earlier rule can be used as an alternative to @Before/@After and @BeforeClass/@AfterClass, we can use @Rule annotation as an alternative to @Before/@After as demonstrated in the example above.

As an alternative to @BeforeClass/@AfterClass Junit provides the @ClassRule annotation.

RELATED ARTICLES

Grouping Of Tests using JUnit Categories

JUnit provides the developers with an opportunity to group multiple tests into a single category, thus creating the possibility to include or exclude the category during execution of the test case.

View Article

Testing Exception and Timeout with JUnit

Apart from testing positive scenarios, JUnit can also be used to test negative scenarios. It can be used to test scenarios where an exception is expected or a timeout is to be checked.

View Article

Unit Testing with JUnit

JUnit is a popular unit testing framework that helps developers to unit test their source code during the development of a java application. This articles demonstrates a basic JUnit Test Case.

View Article

Testing with Multiple Inputs using Parameterized Runner

JUnit Parameterized Test Runners provides the abiltiy to run the same test over and over again using different set of inputs.

View Article

Understanding JUnit Test Suite

A JUnit Test Suite allows developers to bundle multiple test classes together into a single unit (called as test suite) and run them all together at once.

View Article