Friday 6 July 2018

Junit: Create custom rules

You can create a custom rule by implementing 'TestRule' interface.

For example, I created CustomLogger rule, it logs the test case details, before executing actual test case.


CustomLogger.java
package com.sample.customrules;

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

public class CustomLogger implements TestRule {

 @Override
 public Statement apply(Statement base, Description description) {
  return new Statement() {
   @Override
   public void evaluate() throws Throwable {
    System.out.println(description.getDisplayName());
    base.evaluate();
   }
  };
 }

}

TestApp.java
package com.sample.test;

import org.junit.Rule;
import org.junit.Test;

import com.sample.customrules.CustomLogger;

public class TestApp {
 @Rule
 public CustomLogger logger = new CustomLogger();
 
 @Test
 public void testCase1() {
  System.out.println("Executing testCase1");
 }

 @Test
 public void testCase2() {
  System.out.println("Executing testCase2");
 }

 
}


When you run TestApp.java, you can able to see below messages in the console.

testCase1(com.sample.test.TestApp)
Executing testCase1
testCase2(com.sample.test.TestApp)
Executing testCase2

Test Case Execution timer
Calculate and print the execution time of a test case.


TestCaseExecutionTimer.java
package com.sample.customrules;

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

public class TestCaseExecutionTimer implements TestRule{
 @Override
 public Statement apply(Statement base, Description description) {
  return new Statement() {
   @Override
   public void evaluate() throws Throwable {
    long time1 = System.currentTimeMillis();
    base.evaluate();
    long time2 = System.currentTimeMillis();
    
    System.out.println(description.getMethodName() + " takes " + (time2-time1) + " milliseconds");
   }
  };
 }
}

TestApp.java
package com.sample.test;

import org.junit.Rule;
import org.junit.Test;

import com.sample.customrules.TestCaseExecutionTimer;

public class TestApp {
 @Rule
 public TestCaseExecutionTimer timer = new TestCaseExecutionTimer();

 @Test
 public void testCase1() throws InterruptedException {
  System.out.println("Executing testCase1");
  Thread.sleep(500);
 }

 @Test
 public void testCase2() throws InterruptedException {
  System.out.println("Executing testCase2");
  Thread.sleep(100);
 }

}


Run ‘TestApp.java’, you can able to see below messages in console.

Executing testCase1
testCase1 takes 501 milliseconds
Executing testCase2
testCase2 takes 100 milliseconds


Previous                                                 Next                                                 Home

No comments:

Post a Comment