我使用Dagger作为依赖注入框架。到目前为止它运行良好,但我在使用 Dagger 进行 Android 单元测试时遇到问题,无法弄清楚原因(可能是因为不正确使用 Dagger)。
我有以下异常
java.lang.IllegalArgumentException: Failed to construct com.couchsurfing.mobile.android.CSApplication$ProdModule
at dagger.internal.plugins.reflect.ReflectiveModuleAdapter.newModule(ReflectiveModuleAdapter.java:94)
at dagger.internal.RuntimeAggregatingPlugin.getModuleAdapter(RuntimeAggregatingPlugin.java:99)
at dagger.internal.RuntimeAggregatingPlugin.collectIncludedModulesRecursively(RuntimeAggregatingPlugin.java:85)
at dagger.internal.RuntimeAggregatingPlugin.getAllModuleAdapters(RuntimeAggregatingPlugin.java:71)
at dagger.ObjectGraph.makeGraph(ObjectGraph.java:115)
at dagger.ObjectGraph.create(ObjectGraph.java:103)
at com.couchsurfing.mobile.android.core.MessageManagerTest.setUp(MessageManagerTest.java:34)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:190)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:175)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:555)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1661)
Caused by: java.lang.NoSuchMethodException: <init> []
at java.lang.Class.getConstructorOrMethod(Class.java:460)
at java.lang.Class.getDeclaredConstructor(Class.java:588)
at dagger.internal.plugins.reflect.ReflectiveModuleAdapter.newModule(ReflectiveModuleAdapter.java:88)
... 15 more
产生异常的代码如下:
public class MessageManagerTest extends InstrumentationTestCase {
@Inject
MessageManager mMessageManager;
@Inject
MessageOperations.Factory mMOFactory;
@Inject
Context mAppContext;
@Override
public void setUp() {
ObjectGraph.create(new TestModule()).inject(this);
}
@Module(
includes = CSApplication.ProdModule.class,
entryPoints = MessageManagerTest.class,
overrides = true)
static class TestModule {
@Provides
MessageOperations.Factory provideMessageOperationsFactory() {
return Mockito.mock(MessageOperations.Factory.class);
}
@Provides
Context provideAppContext() {
return Mockito.mock(Context.class);
}
}
public void testCreateMessage() throws RemoteException, OperationApplicationException {
...
}
}
请注意,模块CSApplication$ProdModule在应用程序的生产版本中使用并且运行良好。