在用测试覆盖我的完整Android项目时,我正试图找到一种方法来测试我的服务与Robolectric。 我需要测试的服务包含许多需要测试的逻辑。
经过一些研究后,我发现code example from robolectric如何使用shadowService测试服务,但我仍然不知道如何启动服务并测试其功能。
首先,我想创建所有依赖项的模拟并将它们注入服务。然后,对于每个方法,我想编写测试,并且该服务使用不同的模拟依赖方法。
我该怎么做? 测试Android服务时的最佳做法是什么? 有人知道一些好的操作方法吗?
我的测试和服务到目前为止,但服务没有启动(调试器不会进入服务中的断点):
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class , sdk = 23)
public class MyServiceTest {
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock
Context context;
@Mock
ApiService apiService;
@Mock
ServiceManagerImpl serviceManager;
@InjectMocks
private MyService myService;
private ShadowService shadowService;
@Before
public void setUp(){
// explicit service creation from robolectric example
this.updateService = Robolectric.setupService(UpdateService.class);
this.shadowService = shadowOf(this.updateService);
MockitoAnnotations.initMocks(this);
when(this.apiService.fetchData()).thenReturn(42);
}
@Test
public void testService(){
this.updateService.startService(new Intent());
// Test of a service function here ...
}
}
我的服务示例:
public class UpdateService extends Service {
@Inject
Context context;
@Inject
ApiService apiService;
@Inject
ServiceManager serviceManager;
private List<ApkRelease> fetchedData;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
((MyApplication) getApplication()).getComponent().inject(this);
this.fetchData();
return super.onStartCommand(intent, flags, startId);
}
private void fetchData() {
Call<List<Data>> call = this.apiService.getData();
call.enqueue(new Callback<List<Data>>() {
@Override
public void onResponse(Call<List<Data>> call, Response<List<Data>> response) {
if (response.body() != null) {
if (!response.body().isEmpty()) {
fetcheData = response.body();
processNextData();
} else {
stopSelf();
}
}
}
@Override
public void onFailure(Call<List<Data>> call, Throwable t) {
ACRA.getErrorReporter().handleException(t);
startUpgrade();
}
});
}
private void processNextData() {
if (this.fetchedData.isEmpty()) {
startOtherStuff();
return;
}
this.processData(this.fetchedReleases.remove(0));
}
private void processData(Data data, ResponseBody responseBody) {
//process Data
....
this.processNextData();
}
private void startOtherStuff() {
Intent intent = new Intent(this.context, UpgradeService.class);
this.context.startService(intent);
this.stopSelf();
}
...
}