If you use the latest JUnit, you can @Rules become a cleaner solution to your problem. Here is an example:
Imagine this is your application;
package org.zero.samples.junit; public class App { public static void main(String[] args) { System.out.println(new App().getMessage()); } String getMessage() { return "Hello, world!"; } }
This is your test class;
package org.zero.samples.junit; import static org.junit.Assert.*; import org.junit.Rule; import org.junit.Test; public class AppTest { @Rule public RepeatRule repeatRule = new RepeatRule(3);
Create a rule class, for example:
package org.zero.samples.junit; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; public class RepeatRule implements TestRule { private int repeatFor; public RepeatRule(int repeatFor) { this.repeatFor = repeatFor; } public Statement apply(final Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { for (int i = 0; i < repeatFor; i++) { base.evaluate(); } } }; } }
Perform your test case as usual, just this time your test cases will be repeated for a given number of times. You can find some interesting use cases when @Rule can really be useful. Try to create compound rules, the game around you will surely be glued together.
Hope this helps.
Nitin tripathi
source share