20

I´m looking for a way to test an Activity with JUnit4 and the ActivityTestRule, but with a different application class (e.g. mocked or inherited). I was able to get this for library projects using the manifest merge and tools:replace="android:name" on the application tag in the androidTest/AndroidManifest.xml. This however does not work for applications.

Any ideas how this can be done?

Fabian
  • 541
  • 1
  • 6
  • 15

1 Answers1

42

You can subclass the AndroidJUnitRunner with your own runner and override newApplication() with your custom application class.

public class CustomTestRunner extends AndroidJUnitRunner {

@Override
public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    return super.newApplication(cl, CustomTestApplication.class.getName(), context);
}
}

Make sure to update your build.gradle with the new runner like this:

testInstrumentationRunner "com.mypackage.name.path.CustomTestRunner"

Be_Negative
  • 4,892
  • 1
  • 30
  • 33
  • 3
    Thank you for pointing this out: testInstrumentationRunner "com.mypackage.name.path.CustomTestRunner". Many other tutorials failed to do so. – Xi Wei Oct 26 '16 at 20:56
  • 4
    Also, if you're running your test out of Android Studio, you may need to update your `Specific instrumentation runner` in your Run/Debug Configuration to point to your CustomTestRunner equivalent. – Max Nov 19 '16 at 22:04
  • 4
    Is there a way where I can specify some of the test should use `A` as the application class and others use `B` ? Like I want some tests to use Application with dependency injection and some others without. – Sreekanth Mar 27 '19 at 08:42
  • @Sreekanth this can be done via custom test rule. See this comment https://stackoverflow.com/a/36778841/2957893 . Note that it still somehow runs your app but then executes overridenn App class per test – Den Drobiazko Jun 20 '19 at 14:54
  • I can't extend AndroidJUnitRunner. Where can I put to custom runner? – Cafer Mert Ceyhan Jun 26 '20 at 07:09