junit

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;
  }
 
  @Override
  public void evaluate() throws Throwable {
   System.out.println("before: " + name);
   statement.evaluate();
   System.out.println("after: " + name);
  }
 
 }
 
 private final String name;
 
 public LoggingRule(String aName) {
  name = aName;
 }
 
 @Override
 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 {
 
 @ClassRule
 public static LoggingRule classRule = new LoggingRule("classrule");
 
 @Rule
 public static LoggingRule rule = new LoggingRule("rule");
 
 @Test
 public void testSomething() {
  System.out.println("In TestSomething");
  assertTrue(true);
 }
 
 @Test
 public void testSomethingElse() {
  System.out.println("In TestSomethingElse");
  assertTrue(true);
 }
}

Output:

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.
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button