我正在尝试使用Dagger注入服务TelephonyManager
。我正在关注这个sample。我扩展了Application
类以创建图表,并定义了ApplicationModule
,其中包含ServiceModule
,将来还会包含其他模块。
修改
现在系统服务注入Activity
没有任何问题。我在FinderApplication.inject(this)
内遗失了Activity
。它有一个注射,但仍然没有在Robolectric
的测试下注射。我在这篇文章的底部添加了测试用例:
修改-2:
ApplicationModule
已删除并创建了BaseActivity
,其中包含:
((FinderApplication) getApplication()).getGraph().inject(this);
on 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;
}
}
ServiceModule.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;
}
}
}
答案 0 :(得分: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;
}
}
}