我正在学习Retrofit和RxJava以及我创建的测试来连接github:
public class GitHubServiceTests {
RestAdapter restAdapter;
GitHubService service;
@Before
public void setUp(){
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create();
restAdapter = new RestAdapter.Builder()
.setEndpoint("https://api.github.com")
.setConverter(new GsonConverter(gson))
.build();
service = restAdapter.create(GitHubService.class);
}
@Test
public void GitHubUsersListObservableTest(){
service.getObservableUserList().flatMap(Observable::from)
.subscribe(user -> System.out.println(user.login));
}
当我执行测试时,我在控制台中看不到任何内容。但是当我执行另一个测试时
@Test
public void GitHubUsersListTest(){
List<User> users = service.getUsersList();
for (User user : users) {
System.out.println(user.login);
}
它有效,我在控制台中看到用户的登录
这是我的改造界面:
public interface GitHubService {
@GET("/users")
List<User> getUsersList();
@GET("/users")
Observable<List<User>> getObservableUserList();
}
我错了吗?
答案 0 :(得分:4)
由于异步调用,您的测试在下载结果之前完成。这是一个典型的问题,你必须告诉他们。测试等待结果。在简单的java中它将是:
@Test
public void GitHubUsersListObservableTest(){
CountDownLatch latch = new CountDownLatch(N);
service.getObservableUserList()
.flatMap(Observable::from)
.subscribe(user -> {
System.out.println(user.login);
latch.countDown();
});
latch.await();
}
或者您可以使用RxJava中的BlockingObservable:
// This does not block.
BlockingObservable<User> observable = service.getObservableUserList()
.flatMap(Observable::from)
.toBlocking();
// This blocks and is called for every emitted item.
observable.forEach(user -> System.out.println(user.login));