Create and use a gradle or system property in Android Tests

Viewed 637

I am currently running a suite of tests using

adb shell am instrument -w ${PKGNAME}.test/android.support.test.runner.AndroidJUnitRunner

from a bash script. Also, when debugging and writing these tests, I also run them from Android Studio, so I lose the cmd line ability.

What I would like to do is to have a system property or a buildConfig variable that I can set only in my tests, to true, and to be able to use it in my android code.

I can't seem to find a gradle task/config that will set this for this type of test. The only thing I found that was close was testOptions, but this appears to only be for Unit Tests.

2 Answers

The perfect solution would be to figure out how to avoid having to know in code if you are currently in a test at all. You did not explain why you need this info, so take a look at Comtaler's answer to a similar question. It might be just what you need.

To change some settings only for an androidTest / instrumantation / espresso test I came up with the following solution:

 //DbHelper
 public class DbHelper extends SQLiteOpenHelper {
     public static AtomicBoolean isTestMode = new AtomicBoolean(false);

     private static String getDBName() {
       if (isTestMode.get()){
        return null; // use in memory sqlite db
       } else {
        return DB_NAME;
       }
     }

// within my unit test
@Rule
public ActivityTestRule<MyActivity> mActivityRule = new ActivityTestRule<MyActivity>(
        MyActivity.class){

    @Override
    protected void beforeActivityLaunched() {
        super.beforeActivityLaunched();
        DbHelper.isTestMode.set(true);
    }

    @Override
    protected void afterActivityFinished() {
        super.afterActivityFinished();
        DbHelper.isTestMode.set(false);
    }
};
Related