我有简单的应用程序类:
public class MainApplication extends Application {
public MainApplication() throws Exception {
throw new Exception();
}
}
和简单的测试:
public class SimpleTests extends AndroidTestCase {
public void testSum() {
assertEquals(4, 2 + 2);
}
}
为什么我的测试开始时出现异常?我的测试与 Application 类有何关系?
Running tests
Test running startedTest running failed: Instrumentation run failed due to 'java.lang.Exception'
Empty test suite.
Android Studio v.1.5.1
更新:我的 Application 子类当然更复杂,并且在方法“onCreate”中包含业务逻辑。我不想在运行测试时运行此逻辑。
最佳答案
一个选项是覆盖测试的应用程序类。
在 gradle 配置中使用自定义 testInstrumentationRunner:
testInstrumentationRunner 'com.xxx.test.CustomTestRunner'
实现不使用您的 Application 类的 Runner:
public class CustomTestRunner extends InstrumentationTestRunner { @Override public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException { return super.newApplication(cl, Application.class.getName(), context); } }
关于Android 测试在 Application 类中抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34234140/