需求:需要對一個TestCase進行重復(fù)執(zhí)行
之前年少不懂事消请,直接用for循環(huán)去控制TestCase的重復(fù)執(zhí)行栏笆,后來發(fā)現(xiàn)可以用這樣的姿勢:
@Test@Repeat(times = 100)
public void TestCase1(){
}
報錯?莫慌臊泰,這個Repeat規(guī)則還是需要自己實現(xiàn)的蛉加。
該TestRule 的實現(xiàn):
Repeat.java
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Retention( RetentionPolicy.RUNTIME )@Target( { java.lang.annotation.ElementType.METHOD} )
public @interface Repeat {
public abstract int times();
}
編寫一個RepeatRule.java 如:
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
public class RepeatRule implements TestRule {
private static class RepeatStatement extends Statement {
private final int times; private final Statement statement;
private RepeatStatement( int times, Statement statement ) {
this.times = times;
this.statement = statement;}
@Override
public void evaluate() throws Throwable {
for( int i = 0; i < times; i++ ) { statement.evaluate(); } } }
@Override
public Statement apply( Statement statement, Description description ) {
Statement result = statement;
Repeat repeat = description.getAnnotation( Repeat.class );
if( repeat != null ) {
int times = repeat.times();
result = new RepeatStatement( times, statement ); }
return result; }}
最后還需要在測試集中實例化這個Rule類,才能使用,如:
@RunWith(AndroidJUnit4.class)
public class TestCase{
@Rule
public RepeatRule rule = new RepeatRule();
@Test
@Repeat(times = 100) public void TestCase1(){ }}
可以愉快的玩耍了缸逃。
參考:http://www.codeaffine.com/2013/04/10/running-junit-tests-repeatedly-without-loops/