【发布时间】:2014-10-22 12:13:15
【问题描述】:
我正在尝试使用 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 调用,因此我需要伪造响应!
【问题讨论】:
标签: android unit-testing robolectric retrofit rx-java