代码之家  ›  专栏  ›  技术社区  ›  emmby

使用带有InstrumentationTestCase的自定义应用程序

  •  5
  • emmby  · 技术社区  · 14 年前

    我有一个ActivityInstrumentationTestCase2(它是InstrumentationTestCase的一个子类)。当运行我的测试用例时,我需要使用一个定制的TestApplication对象来启动我的活动,因为这个TestApplication对象有一些我的测试所必需的配置。

    但是,我看不到将ActivityInstrumentationTestCase2测试用例自定义为使用测试应用程序对象的方法。有办法吗?

    2 回复  |  直到 13 年前
        1
  •  6
  •   emmby    14 年前

    我不知道是否有更好的方法,但我可以通过使用自定义的TestRunner来实现这一点。

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

    我还需要修改测试项目的AndroidManifest.xml以指定新的运行程序:

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

    我不得不修改我的IDE来使用指定的测试运行器。如果从命令行运行,则需要执行以下操作:

    adb shell am instrument -w com.mypackage/com.mypackage.test.MyInstrumentationTestRunner
    
        2
  •  4
  •   Adel Nizamuddin    11 年前

    应该是

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

    因为它正确地将上下文注入包装器