Home » Core Java » junit » junit rules example

About Byron Kiourtzoglou

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.

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

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of