Retrofitting RxJava Simple Test
I am learning Retrofit and RxJava and I created a test for github connection:
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));
}
when i run the test i dont see anything in my console. But when I do another test
@Test
public void GitHubUsersListTest(){
List<User> users = service.getUsersList();
for (User user : users) {
System.out.println(user.login);
}
it works and i see custom logins in the console
Here's my interface to tweak:
public interface GitHubService {
@GET("/users")
List<User> getUsersList();
@GET("/users")
Observable<List<User>> getObservableUserList();
}
where am i wrong?
+3
source to share
1 answer
Due to the asynchronous call, your test completes before the result is loaded. This is a common problem and you have to "tell" the test to wait for the result. In plain java, this would be:
@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();
}
Or you can use BlockingObservable from RxJava:
// 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));
+4
source to share