Using a custom Application with InstrumentationTestCase

帅比萌擦擦* 提交于 2019-12-22 07:09:18

问题


I have an ActivityInstrumentationTestCase2 (which is a subclass of InstrumentationTestCase). When running my testcases, I need to launch my activities using a custom TestApplication object, since this TestApplication objects has some configuration necessary for my tests.

However, I don't see a way to customize my ActivityInstrumentationTestCase2 testcases to use the test Application object. Is there a way to do so?


回答1:


I don't know if there's a better way, but I was able to accomplish this by using a custom TestRunner.

public class MyInstrumentationTestRunner extends InstrumentationTestRunner {

    @Override
    public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        return new MyTestApplication(context);       
    }


}

I also needed to modify my test project's AndroidManifest.xml to specify the new runner:

<instrumentation android:name="com.mypackage.test.MyInstrumentationTestRunner" ... />

And I had to modify my IDE to use the specified test runner as well. If you're running from the command line, you'll need to do something like the following instead:

adb shell am instrument -w com.mypackage/com.mypackage.test.MyInstrumentationTestRunner



回答2:


It should be

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

Because it injects Context to a wrapper correctly



来源:https://stackoverflow.com/questions/4159387/using-a-custom-application-with-instrumentationtestcase

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!