1

我一直试图将我的自定义应用程序“注入”到 ActivityInstrumentationTestCase2。

为了能够进行单元测试和注入,我的应用程序实现了这样的接口:

public interface DaggerGraphInjection {
    public ObjectGraph getObjectGraph();
}

在活动中,我使用以下方法获取图表:

DaggerGraphInjection injector = (DaggerGraphInjection) getApplication();
injector.getObjectGraph().inject(this);

使用这种接口,我可以在我的单元测试中注入模拟依赖项。但是当我想运行功能测试时,我得到了下一个异常:

10-11 08:57:32.588  17879-17879/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.foo.bar/com.foo.bar.activities.MyCalendarActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to com.foo.bar.DaggerGraphInjection
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
            at android.app.ActivityThread.access$700(ActivityThread.java:140)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4921)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to com.foo.bar.DaggerGraphInjection
            at com.foo.bar.activities.MyCalendarActivity.onCreate(MyCalendarActivity.java:47)
            at android.app.Activity.performCreate(Activity.java:5206)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
            at android.app.ActivityThread.access$700(ActivityThread.java:140)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4921)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
            at dalvik.system.NativeStart.main(Native Method)

那是因为,这种测试在没有实现我的接口的情况下注入了默认应用程序,我的问题是:任何可能的解决方案是否像自定义 TestRunner 或类似的东西?

谢谢 :)

4

0 回答 0