【问题标题】:How to write a unit test to verify returning Observable?如何编写单元测试来验证返回的 Observable?
【发布时间】:2019-06-13 12:14:35
【问题描述】:

我有一个 ApiRepository 类,它将包含我所有的 API 调用,但目前只有一个:

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);
}
}

RestClient 界面如下所示:

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

所以,我尝试运行通过的测试,但是当我生成代码覆盖率报告时,返回的代码行是红色的。

这是我的测试类:

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));

}
}

我相信测试通过了,但没有得到任何验证,对吧?这不应该是什么时候 - 那么返回就足够了吗?

【问题讨论】:

  • 答案是:你是对的,没有任何东西被验证,当 - then 是不够的。请参考文档How do I ask a good question?
  • 真正的问题是是否值得测试这种简单的委托。老实说,只要这里没有任何逻辑,我就不会理会它。你最终会得到更多的代码和几乎为零的价值。

标签: android unit-testing mockito observable rx-java2


【解决方案1】:

就我个人而言,我不会让存储库成为间谍,所以在设置中我会:

@Before
public void setUp() {
   MockitoAnnotations.initMocks(this);
   restApiRepository = 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));

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

通过这种方式,您可以断言 observable 发出所需的值。 test 是一个方便的 Rx 方法,它订阅并创建一个测试观察者,让您对不同的事件进行断言。

另外,我不会将存储库设置为间谍的原因仅仅是因为您实际上不需要验证与它的任何交互,只需要验证它的依赖关系。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-10
    相关资源
    最近更新 更多