简体   繁体   中英

How to write a unit test to verify returning Observable?

I have an ApiRepository class which will contain all my API calls, but currently only has one:

public class RestApiRepository {

private RestClient restClient;

public RestApiRepository(RestClient restClient) {
    this.restClient= restClient;
}


public Observable<AuthResponseEntity> authenticate(String header, AuthRequestEntity requestEntity) {
    return restClient.postAuthObservable(header, requestEntity);
}
}

And RestClient interface looks like this:

public interface SrsRestClient {
    @POST(AUTH_URL)
Observable<AuthResponseEntity> postAuthObservable(@Header("Authorization") String authKey, @Body AuthRequestEntity requestEntity);
}

So, I tried to run the test which passed, but when I generate a code coverage report, that return line of code is red.

Here's my test class:

public class RestApiRepositoryTest {

private RestApiRepository restApiRepository;

@Mock
private RestClient restClient;

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    restApiRepository = Mockito.spy(new RestApiRepository(restClient));
}

@Test
public void test_success() {
    String token = "token";
    AuthRequestEntity requestEntity = new AuthRequestEntity();
    AuthResponseEntity responseEntity = new AuthResponseEntity();
    Mockito.when(restClient.postAuthObservable(token, requestEntity)).thenReturn(Observable.just(responseEntity));

}
}

I believe the test passed, but nothing is verified, right? Shouldn't this when - then return would be enough?

Personally I wouldn't make the repository a spy, so in setup I'd have:

@Before
public void setUp() {
   MockitoAnnotations.initMocks(this);
   restApiRepository = new RestApiRepository(restClient);
}

Now I'd write the test like:

@Test
public void test_success() {
  String token = "token";
  AuthRequestEntity requestEntity = new AuthRequestEntity();
  AuthResponseEntity responseEntity = new AuthResponseEntity();
  Mockito.when(restClient.postAuthObservable(token, requestEntity)).thenReturn(Observable.just(responseEntity));

  restApiRepository.authenticate(token, responseEntity)
        .test()
        .assertValue(responseEntity)
 }

This way you are asserting that the observable emits the desired value. test is a handy Rx method that subscribes and creates a test observer that lets you assert on different events.

Also, the reason I wouldn't make the repository a spy is simply because you don't really need to verify any interactions with it, just its dependencies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM