简体   繁体   English

如何测试Retrofit2 + RxJava2 api调用?

[英]How to test Retrofit2 + RxJava2 api call?

I am wondering how to test Retrofit2 call via rxjava2. 我想知道如何通过rxjava2测试Retrofit2调用。 My retrofit api interface looks like: 我的改装api界面如下:

public interface LoginApiMapping {
   @POST("v1/secm/oam/oauth2/token")
   Observable<Response<RestResponseHolder<LoginResponseModel>>> login(@Body LoginModel model);
}

and i would like to write the test which will send this request via RxJava2 and check the response. 我想编写测试,它将通过RxJava2发送此请求并检查响应。 I consider that there is the problem with RxJava as it is asynchronous and the test finishes before i get the response, so i tried to use TestSubscriber as below, but it's not possible to subscribe TestSubscriber<Response<RestResponseHolder<LoginResponseModel>>> as i expected 我认为RxJava存在问题,因为它是异步的,测试在我得到响应之前完成,所以我尝试使用如下的TestSubscriber,但是不可能订阅TestSubscriber <Response <RestResponseHolder <LoginResponseModel >>>作为我预期

@Test
public void loginTest(){
    Context appContext = InstrumentationRegistry.getTargetContext();
    Api t = TestApi.create(appContext);
    LoginModel loginModel = new LoginModel("username","password");
    TestSubscriber<Response<RestResponseHolder<LoginResponseModel>>> testSubscriber = new TestSubscriber<>();
    t.get(LoginApiMapping.class).login(loginModel).subscribe(testSubscriber);
}

anyone who solved that? 有谁解决了这个问题? thanks 谢谢

I finally found the solution, so i decided to post it here. 我终于找到了解决方案,所以我决定在这里发布。 First you have to call toFlowable() on the observable and set the Backpressure strategy and then you can subscribe with TestSubscriber as below 首先,您必须在observable上调用Flowable()并设置Backpressure策略,然后您可以使用TestSubscriber订阅,如下所示

t.get(LoginApiMapping.class).login(loginModel).toFlowable(BackpressureStrategy.DROP).subscribe(testSubscriber);

Then add 然后加

testSubscriber.awaitTerminalEvent();

at the end that you can check various assertions on testSubscriber as R. Zagórski pointed in answer above. 最后,您可以检查testSubscriber上的各种断言,如Z.Zagórski在上面的回答中指出的那样。

At the end of of test add: 在测试结束时添加:

testSubscriber.awaitTerminalEvent();

Then you can check various assertions on testSubscriber . 然后你可以检查testSubscriber上的各种断言。

You use TestSubscriber with Flowable and TestObserver with Observable. 您将TestSubscriber与Flowable一起使用,TestObserver与Observable一起使用。 You can test Single, Completable and Maybe by converting them to either Flowable or Observable, but the built-in test()s for these three return TestSubscriber. 您可以通过将它们转换为Flowable或Observable来测试Single,Completable和Maybe,但是这三个的内置test()返回TestSubscriber。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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