我正在尝试使用Robolectric编写一段代码的单元测试,但问题在于我需要伪造http调用,而Robolectric的伪造层似乎只能与Apache的HttpClient一起使用,正如这个答案所述:链接。在Retrofit中,您无法更改URL,因此MockWebServer似乎不是一个选项。看起来mockito可以捕获retrofit回调,但我正在使用rxJava,所以我不知道它是否有帮助。是否有人对使用Robolectric + Retrofit + okHttp + rxJava进行单元测试有任何建议?下面是一小段示例代码:
Robolectric.addPendingHttpResponse无论如何也行不通,因为OkHttp的缘故。API调用是在按下按钮时启动的,所以我需要在那个时刻伪造响应!
@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();
}
Robolectric.addPendingHttpResponse无论如何也行不通,因为OkHttp的缘故。API调用是在按下按钮时启动的,所以我需要在那个时刻伪造响应!