Can I extend a custom Application in Espresso?

With a custom instrumentation runner, you can override newApplication and have it instantiate something other than the default application from the manifest.

public class MyRunner extends AndroidJUnitRunner {
  @Override
  public Application newApplication(ClassLoader cl, String className, Context context)
      throws Exception {
    return super.newApplication(cl, MyCustomEspressoApplication.class.getName(), context);
  }
}

Be sure to update testInstrumentationRunner with your custom runner's name.


Took me an entire day to get the complete answer.

Step 1: Override AndroidJUnitRunner

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

Step 2: replace the existing AndroidJunitRunner in build.gradle

defaultConfig {
    ...
    // testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    testInstrumentationRunner 'com.xi_zz.androidtest.TestRunner'
}

Step 3: Add com.android.support.test:runner to build.gradle

androidTestCompile 'com.android.support.test:runner:0.5'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'

Step 4: Only if you got this error

Warning:Conflict with dependency 'com.android.support:support-annotations'. Resolved versions for app (25.2.0) and test app (23.1.1) differ. See http://g.co/androidstudio/app-test-app-conflict for details.

Then, add one more line:

androidTestCompile 'com.android.support:support-annotations:25.2.0'
androidTestCompile 'com.android.support.test:runner:0.5'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'

Finally, test if it works

@RunWith(AndroidJUnit4.class)
public class MockApplicationTest
{
    @Rule
    public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(MainActivity.class);

    @Test
    public void testApplicationName() throws Exception
    {
        assertEquals("TestApplication", mActivityRule.getActivity().getApplication().getClass().getSimpleName());
    }
}