AndroidJunit4 之重复执行Case

需求:需要对一个TestCase进行重复执行
之前年少不懂事,直接用for循环去控制TestCase的重复执行,后来发现可以用这样的姿势:

@Test@Repeat(times = 100)
public void TestCase1(){
}

报错?莫慌,这个Repeat规则还是需要自己实现的。
该TestRule 的实现:
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/

你可能感兴趣的:(AndroidJunit4 之重复执行Case)