18

I am using Espresso 2.1 with ActivityTestRule, and I am looking for a way to set some static flags before onCreate() in my application will be called.

I have some init code that I don't want called during instrumentation tests.

shkschneider
  • 17,833
  • 13
  • 59
  • 112
smdremedy
  • 288
  • 2
  • 8

1 Answers1

29

Application onCreate() is called after Instrumentation onCreate(). For this case you need to implement a custom test runner which will subclass AndroidJUnitRunner and will override the callApplicationOnCreate() with your custom setup.

public class MyCustomTestRunner extends AndroidJUnitRunner {
@Override
public void callApplicationOnCreate(Application app) {
    InstrumentationRegistry.getTargetContext().getSharedPreferences().doMyStuff();
    super.callApplicationOnCreate(app);
}
}

Make sure to update your defaultConfig in the build.gradle to use new testInstrumentationRunner like this:

testInstrumentationRunner "com.myapp.MyCustomTestRunner"

If you are looking to run some code before Activity onCreate(), subclass ActivityTestRule with your own implementation of beforeActivityLaunched()

Be_Negative
  • 4,892
  • 1
  • 30
  • 33
  • This doesn't work for Junit 4 tests. Have you had any luck using AndroidJUnit4 ? – Marco RS Nov 22 '15 at 20:41
  • This is for junit4 tests. I think you are mixing two things - a class runner and [instrumentation runner](http://developer.android.com/reference/android/support/test/runner/AndroidJUnitRunner.html). Class runner remains the same (AndroidJUnit4), while your instrumentation runner is a custom one. It's actually quite interesting - I completely forgot to annotate some of the classes with @runwith and it didn't seem to impact anything. I am not sure if you even need it anymore, unless you have some customization going on. – Be_Negative Nov 23 '15 at 00:06
  • Thanks that was very helpful. I'm now however experiencing an error where I get the error "Test running failed: Unable to find instrumentation info for: ComponentInfo{com.mypackage.test/android.support.test.runner.AndroidJUnitRunner}" . How do I properly set testInstrumentationRunner in build.gradle? Thanks again. – Marco RS Nov 23 '15 at 01:28
  • 1
    Oh,this one is in the ```android { defaultConfig { testInstrumentationRunner "com.myapp.MyCustomTestRunner" }}``` of your app gradle file. Make sure to update the run configuration in your IDE as well. If you are using android studio it's in the "Specific Instrumentation Runner" . – Be_Negative Nov 23 '15 at 01:50
  • 13
    Is it possible to use this runner for only some tests? – Joe Maher Mar 31 '17 at 06:07