Android unit test config conditionally ignore

  • Add a config file, perhaps place it in project root folder:
    For example, if the test methods are testA and testB:
    config.ini
testA=Y
testB=N
  • Add a gradle task in $rootDir to move the config file to Assets folder.(Perhaps manually create an asset folder first?)
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


task copyConfig(type: Copy) {
    description = "Copy the config file from the project root folder to 'app/src/main/assets/', if the config file exists in root folder."
    if (file("config.ini").exists()) {
        println "The 'config.ini' exists in root folder, copy to assert now."
        from "$rootDir/config.ini"
        into "app/src/main/assets/"
    } else {
        println "The 'config.ini' does not exist in root folder. Will run default tests."
    }
}
In this case, a gradle task will run first ./gradlew copyConfig, then ./gradlew --build-cache connectedDebugAndroid.
  • Add a java file to the AndroidTest:
package com.XXX.YYY;

import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Modifier;

import org.junit.Assume;
import org.junit.rules.MethodRule;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;

public class ConditionalIgnoreRule implements MethodRule {

    public interface IgnoreCondition {
        boolean isSatisfied() throws IOException;
    }

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.METHOD})
    public @interface ConditionalIgnore {
        Class<? extends IgnoreCondition> condition();
    }

    @Override
    public Statement apply( Statement base, FrameworkMethod method, Object target ) {
        Statement result = base;
        if( hasConditionalIgnoreAnnotation( method ) ) {
            IgnoreCondition condition = getIgnoreContition( target, method );
            try {
                if( condition.isSatisfied() ) {
                    result = new IgnoreStatement( condition );
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    private static boolean hasConditionalIgnoreAnnotation( FrameworkMethod method ) {
        return method.getAnnotation( ConditionalIgnore.class ) != null;
    }

    private static IgnoreCondition getIgnoreContition( Object target, FrameworkMethod method ) {
        ConditionalIgnore annotation = method.getAnnotation( ConditionalIgnore.class );
        return new IgnoreConditionCreator( target, annotation ).create();
    }

    private static class IgnoreConditionCreator {
        private final Object target;
        private final Class<? extends IgnoreCondition> conditionType;

        IgnoreConditionCreator( Object target, ConditionalIgnore annotation ) {
            this.target = target;
            this.conditionType = annotation.condition();
        }

        IgnoreCondition create() {
            checkConditionType();
            try {
                return createCondition();
            } catch( RuntimeException re ) {
                throw re;
            } catch( Exception e ) {
                throw new RuntimeException( e );
            }
        }

        private IgnoreCondition createCondition() throws Exception {
            IgnoreCondition result;
            if( isConditionTypeStandalone() ) {
                result = conditionType.newInstance();
            } else {
                result = conditionType.getDeclaredConstructor( target.getClass() ).newInstance( target );
            }
            return result;
        }

        private void checkConditionType() {
            if( !isConditionTypeStandalone() && !isConditionTypeDeclaredInTarget() ) {
                String msg
                        = "Conditional class '%s' is a member class "
                        + "but was not declared inside the test case using it.\n"
                        + "Either make this class a static class, "
                        + "standalone class (by declaring it in it's own file) "
                        + "or move it inside the test case using it";
                throw new IllegalArgumentException( String.format ( msg, conditionType.getName() ) );
            }
        }

        private boolean isConditionTypeStandalone() {
            return !conditionType.isMemberClass() || Modifier.isStatic( conditionType.getModifiers() );
        }

        private boolean isConditionTypeDeclaredInTarget() {
            return target.getClass().isAssignableFrom( conditionType.getDeclaringClass() );
        }
    }

    private static class IgnoreStatement extends Statement {
        private final IgnoreCondition condition;

        IgnoreStatement( IgnoreCondition condition ) {
            this.condition = condition;
        }

        @Override
        public void evaluate() {
            Assume.assumeTrue( "Ignored by " + condition.getClass().getSimpleName(), false );
        }
    }

}
  • Add this to the test class:
    @Rule
    public ConditionalIgnoreRule rule = new ConditionalIgnoreRule();
  • Write a method to read from assert:
public String readFromConfig(Context ctx, String configFileName) {
        InputStream in = null;
        try {
            in = ctx.getAssets().open(configFileName);
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder builder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line).append(System.getProperty("line.separator"));
            }
            in.close();
            reader.close();
            String config = builder.toString();
            Log.v(LOG_TAG, "readFromConfig: The config content is:");
            Log.v(LOG_TAG, "*********************************");
            Log.v(LOG_TAG, config);
            Log.v(LOG_TAG, "*********************************");
            return config;
        } catch (IOException e) {
            e.printStackTrace();
            Log.d(LOG_TAG, "readFromConfig: The 'config.ini' file is missing in the assets folder.");
            Log.d(LOG_TAG, "readFromConfig: Will ignore the config and run all tests.");
            return null;
        }
  • Write a method to check if a specific method will run or skip:
    public boolean willRun(Context ctx, String configFileName, String caseName) throws IOException {
        String config = readFromConfig(ctx, configFileName);
        return config == null || config.contains(caseName);
    }

  • Write a class for each test, for instance, if your test name is testA(this class can be written within the test class):
public class IgnoreTestA implements ConditionalIgnoreRule.IgnoreCondition {

        @Override
        public boolean isSatisfied() {
            try {
                //If return true, will skip the test; Else will run it.
                return willRun(ctx, CONFIG_FILE_NAME, "testA=Y");
            } catch (IOException e) {
                e.printStackTrace();
            }
            //If config file not found, consider default as "Run all".
            return false;
        }
    }
  • Add an annotation to the test method:
@ConditionalIgnoreRule.ConditionalIgnore( condition = IgnoreTestA.class )
@Test
public void testA() {
     ...
}

Finally, we can decide a test will run or skip according to the config file.

And alternatively, if we just want to conditionally skip a test, but do not care whether the @Before and @After will run accordingly or not, we can just do this:

@Test
public void testA() {
    Assume.assumeFalse(willRun(ctx, CONFIG_FILE_NAME, "testA=Y"));
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,445评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,889评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,047评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,760评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,745评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,638评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,011评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,669评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,923评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,655评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,740评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,406评论 4 320
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,995评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,961评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,197评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,023评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,483评论 2 342

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,283评论 0 10
  • This project was bootstrapped with Create React App. Belo...
    unspecx阅读 5,132评论 0 2
  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom阅读 2,689评论 0 3
  • 结束待在家度假般的生活,回到学校,一切开始进入正轨。 今天在大巴上的时候就开始觉得心里着急,于是不过稍微的了解了之...
    山顶的黑狗兄阅读 169评论 0 1
  • 天气预报提前三天通知广大市民,接下来会有三天的回南天。 三天后,阳光明媚的天气准时灰了天,暗了光线。 黑压压的天空...
    暖笑如云阅读 112评论 0 0