6

我正在尝试TelephonyManager用 Dagger 注入服务。我正在关注这个示例。我扩展了Application该类以创建图形并定义了包含的ApplicationModule位置ServiceModule,并且将来将包含其他模块。

编辑:

现在系统服务被注入到一个Activity没有任何问题的地方。FinderApplication.inject(this)我在里面失踪了Activity。它有一个注入,但在测试中仍然没有注入Robolectric. 我在这篇文章的底部添加了测试用例:

Edit-2: ApplicationModule删除并创建BaseActivity

((FinderApplication) getApplication()).getGraph().inject(this);

关于onCreate方法。我得到的错误是:

引起:java.lang.NoSuchMethodException: ServiceModule.()

但是如果我定义一个空的构造函数,当需要注入的类时,我会得到一个空指针。

FinderApplication.java

public class FinderApplication extends Application {
    private ObjectGraph mObjectGraph;

    @Override
    public final void onCreate() {
        super.onCreate();
        mObjectGraph = ObjectGraph.create(new ServiceModule(this));
    }

    public final ObjectGraph getGraph() {
        return mObjectGraph;
    }
}

服务模块.java

@Module(entryPoints = { SimCardActivity.class, SimService.class })
public class ServiceModule {

    private Context mContext;

    public ServiceModule(Context context) {
        mContext = context;
    }

    @Provides @Singleton
    TelephonyManager provideTelephonyManager(){
        return (TelephonyManager) mContext
            .getSystemService(Context.TELEPHONY_SERVICE);
    }
}

SimCardActivityTest.java

@RunWith(RobolectricTestRunner.class)
public class SimCardActivityTest { 

    @Before
    public void setUp() throws Exception {
        ObjectGraph.create(new TestModule()).inject(this);;
    }

    @Module(
            includes = ServiceModule.class,
            overrides = true,
            entryPoints = {SimCardActivityTest.class, SimCardActivity.class}
    )
    static class TestModule{
        public static TelephonyManager TELEPHONY_MANAGER = 
            Mockito.mock(TelephonyManager.class);

        @Provides @Singleton
        TelephonyManager provideTelephonyManager(){
            return TELEPHONY_MANAGER;
        }
    }
}
4

1 回答 1

3

正如@AndyDennie 在他的评论中所说,我在测试课上没有进行任何注射。注入被测活动而不是创建它setUp()解决了问题。

我当前的测试用例(相关代码)如下所示:

@RunWith(RobolectricTestRunner.class)
public class SimCardActivityTest {

    @Inject
    private SimCardActivity mActivity;

    private TelephonyManager mTelephonyManager;

    @Before
    public void setUp() throws Exception {
        ObjectGraph.create(new ServiceModule(Robolectric.application), 
                           new ServiceTestModule()).inject(this);
    }

    @Module(
            includes = {ServiceModule.class },
            overrides = true,
            entryPoints = {SimCardActivity.class, SimCardActivityTest.class}
    )
    static class ServiceTestModule {
        public static TelephonyManager TELEPHONY_MANAGER = 
            Mockito.mock(TelephonyManager.class);

        @Provides
        @Singleton
        TelephonyManager provideTelephonyManager(){
            return TELEPHONY_MANAGER;
        }
    }
}
于 2013-03-08T19:15:17.030 回答