我想知道如何通过Retrofit2测试rxjava2调用。我的改进api接口如下所示:
public interface LoginApiMapping {
@POST("v1/secm/oam/oauth2/token")
Observable<Response<RestResponseHolder<LoginResponseModel>>> login(@Body LoginModel model);
}我想写一个测试,它将通过RxJava2发送这个请求并检查响应。我认为RxJava存在问题,因为它是异步的,并且测试在得到响应之前就完成了,所以我尝试按下面的方式使用TestSubscriber,但是不可能像我预期的那样订阅TestSubscriber>
@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);
}有人解决了这个问题吗?谢谢
发布于 2017-03-24 13:54:55
我终于找到了解决办法,所以我决定把它发到这里。首先,您必须调用可观察到的toFlowable()并设置背压策略,然后您可以订阅TestSubscriber,如下所示
t.get(LoginApiMapping.class).login(loginModel).toFlowable(BackpressureStrategy.DROP).subscribe(testSubscriber);然后添加
testSubscriber.awaitTerminalEvent();最后,您可以检查testSubscriber上的各种断言,正如R.Zagórski在上面的回答中指出的那样。
发布于 2017-03-17 14:36:36
在测试的末尾加上:
testSubscriber.awaitTerminalEvent();然后,您可以检查testSubscriber上的各种断言。
发布于 2017-09-26 14:27:55
您将TestSubscriber用于可流动,而TestObserver用于可观察。您可以测试单个的、可完成的,也可以通过将它们转换为可流动的或可观察的,但是这三个返回TestSubscriber的内置test()s。
https://stackoverflow.com/questions/42858944
复制相似问题