JUnit Rules Example

The implementation of a Rule might look like this:

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
public class LoggingRule implements TestRule {
 public class LoggingStatement extends Statement {
  private final Statement statement;
  public LoggingStatement(Statement aStatement, String aName) {
   statement = aStatement;
  public void evaluate() throws Throwable {
   System.out.println("before: " + name);
   System.out.println("after: " + name);
 private final String name;
 public LoggingRule(String aName) {
  name = aName;
 public Statement apply(Statement statement, Description description) {
  System.out.println("apply: " + name);
  return new LoggingStatement(statement, name);

A test class using this Rule might look like this:

import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
public class RuleTest {
 public static LoggingRule classRule = new LoggingRule("classrule");
 public static LoggingRule rule = new LoggingRule("rule");
 public void testSomething() {
  System.out.println("In TestSomething");
 public void testSomethingElse() {
  System.out.println("In TestSomethingElse");


apply: classrule
before: classrule
apply: rule
before: rule
In TestSomething
after: rule
apply: rule
before: rule
In TestSomethingElse
after: rule
after: classrule

Related Article:

Reference: Rules in JUnit 4.9 (beta 3) from our JCG partner Jens Schauder at the Schauderhaft blog

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button