2013-01-10 39 views
1

我正在使用Dagger作为依赖注入框架。目前为止效果很好,但我在使用Dagger进行Android单元测试时遇到了问题,无法弄清楚原因(可能是因为使用了Dagger)。匕首在创建图时抛出NoSuchMethodException

我有以下异常

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中的量产版使用应用程序并运行良好。

回答

3

您需要给ProdModule一个无参数非私有构造函数。课堂需要是静态的。没有这个匕首不能构建你的模块。

1

您需要添加一个无参数(在本例中为public)构造函数,或者您需要传递该模块的一个实例。如果你没有传入一个实例,那么Dagger必须构造模块本身,如果没有可访问的无参数构造函数,它就无法做到。