我想知道如何通过rxjava2测试Retrofit2调用。我的改装api界面如下:
public interface LoginApiMapping {
@POST("v1/secm/oam/oauth2/token")
Observable<Response<RestResponseHolder<LoginResponseModel>>> login(@Body LoginModel model);
}
我想编写测试,它将通过RxJava2发送此请求并检查响应。我认为RxJava存在问题,因为它是异步的,测试在我得到响应之前完成,所以我尝试使用如下的TestSubscriber,但是不可能订阅TestSubscriber&lt; Response&lt; RestResponseHolder&lt; LoginResponseModel&gt;&gt;&gt;正如我所料
@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);
}
谁解决了这个问题?感谢
答案 0 :(得分:3)
我终于找到了解决方案,所以我决定在这里发布。 首先,您必须在observable上调用Flowable()并设置Backpressure策略,然后您可以使用TestSubscriber订阅,如下所示
t.get(LoginApiMapping.class).login(loginModel).toFlowable(BackpressureStrategy.DROP).subscribe(testSubscriber);
然后添加
testSubscriber.awaitTerminalEvent();
最后你可以检查testSubscriber上的各种断言,就像R.Zagórski在上面的回答中指出的那样。
答案 1 :(得分:1)
在测试结束时添加:
testSubscriber.awaitTerminalEvent();
然后你可以检查testSubscriber
上的各种断言。
答案 2 :(得分:0)
您使用带有Flowable的TestSubscriber和带有Observable的TestObserver。您可以通过将它们转换为Flowable或Observable来测试Single,Completable和Maybe,但是这三个的内置test()将返回TestSubscriber。