我正在尝试用robolectric编写一段代码的单元测试.问题是我需要伪造http调用,但似乎robolectric的假层只适用于Apache的HttpClient,根据这个答案:
链接回答
在Retrofit中,您无法更改URL,因此MockWebServer似乎不是一个选项.
似乎mockito可以捕获改进的回调,但我正在使用rxJava,所以我真的不知道它是否有帮助.
有没有人对Robolectric + Retrofit + okHttp + rxJava的单元测试有任何建议?
这是一小段代码:
@Test public void test1() throws IOException, InterruptedException { FragmentA frag = (FragmentA) activity .getFragmentManager().findFragmentById( R.id.frag); assertThat(frag).isNotNull(); assertThat(frag.isVisible()).isTrue(); EditText input1 = (EditText) frag.getView() .findViewById(R.id.edit_text1); EditText input2 = (EditText) frag.getView() .findViewById(R.id.edit_text2); Button button = (button) frag.getView() .findViewById(R.id.button); input1.setText("999"); input2.setText("999"); Robolectric.addPendingHttpResponse(200, "{\"isValid\": true}"); button.performClick(); assertThat( ShadowAlertDialog.getLatestDialog() instanceof ProgressDialog) .isTrue(); }
由于OkHttp,Robolectric.addPendingHttpResponse无论如何都不会起作用.按下按钮时启动api调用,因此我需要伪造响应!