By
using RuleChain, we can execute the test rules in specific order.
TestCaseExecutionTimer.java
TestApp.java
Example
In
the above esample, CustomLogger rule is executed first followed by
TestCaseExecutionTimer rule.
Find
the below working application.
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("Executing : " + description.getMethodName()); base.evaluate(); System.out.println("Execution done for : " + description.getMethodName()); } }; } }
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(); if (description.getMethodName() != null) { System.out.println(description.getMethodName() + " takes " + (time2 - time1) + " milliseconds"); } else { System.out.println("Test cases in " + description.getClassName() + " takes " + (time2 - time1) + " milliseconds"); } } }; } }
TestApp.java
package com.sample.test; import org.junit.Rule; import org.junit.Test; import org.junit.rules.RuleChain; import com.sample.customrules.CustomLogger; import com.sample.customrules.TestCaseExecutionTimer; public class TestApp { @Rule public RuleChain chain = RuleChain. outerRule(new CustomLogger()). around(new TestCaseExecutionTimer()); @Test public void testCase1() throws InterruptedException { Thread.sleep(500); } @Test public void testCase2() throws InterruptedException { Thread.sleep(100); } }
Run
TestApp.java, you can able to see below messages in console.
Executing
: testCase1
testCase1
takes 503 milliseconds
Execution
done for : testCase1
Executing
: testCase2
testCase2
takes 101 milliseconds
Execution
done for : testCase2
No comments:
Post a Comment