相关疑难解决方法(0)

Robolectric + OkHttp +改造+ rxJava单元测试

我正在尝试用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();

  }
Run Code Online (Sandbox Code Playgroud)

由于OkHttp,Robolectric.addPendingHttpResponse无论如何都不会起作用.按下按钮时启动api调用,因此我需要伪造响应!

android unit-testing robolectric rx-java retrofit

7
推荐指数
1
解决办法
2045
查看次数

任何人都成功用Robolectric嘲笑HttpRequests?

我刚刚开始使用Robolectric.它似乎可以很好地模拟大多数Android类,但是当我的测试类试图创建一个DefaultHttpClient()时,它会得到可怕的"Stub!".错误.

被测试的课程在这一行失败:

HttpClient httpclient = new DefaultHttpClient();
Run Code Online (Sandbox Code Playgroud)

尽管http://robolectric.blogspot.com/2011/01/how-to-test-http-requests.html?showComment=1297722651278#c3540420071421225744上的文章似乎表明这应该可行.

我的测试看起来像这样:

@Before
public void setUp() throws Exception
{
  Robolectric.addPendingHttpResponse(200, "OK");
  service = new CheckinService();
}

@Test
public void testIt() throws IOException
{
  // Fails at HttpClient httpclient = new DefaultHttpClient()
  service.doStuff(Robolectric.application,
                  REG_ID,
                  TEST_DOMAIN);
}
Run Code Online (Sandbox Code Playgroud)

知道我做错了什么吗?

testing android http mocking

4
推荐指数
1
解决办法
1279
查看次数