Dem0n13 Dem0n13 -4 years ago 124
Android Question

Android tests throws exception in Application class

I have simple Application class:

public class MainApplication extends Application {
public MainApplication() throws Exception {
throw new Exception();

and simple test:

public class SimpleTests extends AndroidTestCase {
public void testSum() {
assertEquals(4, 2 + 2);

why I get an Exception on my tests starting? How my test is related with the Application class?

Running tests
Test running startedTest running failed: Instrumentation run failed due to 'java.lang.Exception'
Empty test suite.

Android Studio v.1.5.1

UPDATE: my Application subclass of course is more complex and contains business logic in method "onCreate". I do not want to run this logic when I run my tests.

Answer Source

An option is override Application class for tests.

  1. Use custom testInstrumentationRunner in gradle configuration:

    testInstrumentationRunner ''
  2. Implement Runner that doesn't use your Application class:

    public class CustomTestRunner extends InstrumentationTestRunner {
        public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
            return super.newApplication(cl, Application.class.getName(), context);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download