让我们假设您有下一个代码.接口:
@GET("/user/{id}/photo")
void listUsers(@Path("id") int id, Callback cb);
执行:
public void fetchData() {
RestAdapter restAdapter = new RestAdapter.Builder()
.setServer("baseURL")
.build();
ClientInterface service = restAdapter.create(ClientInterface.class);
Callback callback = new Callback() {
@Override
public void success(Photo o, Response response) {
}
@Override
public void failure(RetrofitError retrofitError) {
}
};
service.listUsers(435, callback);
}
首先,您需要将服务实例化更改为服务注入(作为参数或字段).我会把它作为参数:
public void fetchData(ClientInterface clients) {
}
在这篇文章非常简单之后:
@Test
public void checkThatServiceSuccessIsProcessed() {
ClientInterface mockedClients = mock(ClientInterface.class);
activity.fetchData(mockedClients);
// get callback
ArgumentCaptor> captor = (ArgumentCaptor>)ArgumentCaptor.forClass(Callback.class);
verify(mockedInterface).listUsers(anything(), captor.capture());
Callback passedCallback = captor.value();
// run callback
callback.success(...);
// check your conditions
}
用于模拟和验证的二手库是Mockito.
由于泛型,将有一个警告与captor实例化,但如果您将使用@Captor注释而不是手动创建captor,则可以修复它.
参数注入并不完美,特别是对于活动情况.这用于简化示例.考虑正确注入库或不使用库.我鼓励你尝试Dagger注射