2

在我的应用程序中,我将在 POST 请求中向服务器发送 JSON。

我想测试以确保我发送了正确的值。

由于我使用的是 Robolectric,我的结论是我应该获取发送到 FakeHttpLayer的请求,提取 JSON,并测试它是否符合我的期望。

听起来很简单,但我花了很长时间弄清楚如何查看我发布的 JSON。

我的代码模糊地看起来像这样:

HttpClient client = new DefaultHttpClient();
HttpResponse response;
JSONObject json = new JSONObject();
try{
    HttpPost post = new HttpPost("http://google.com");
    json.put("blah", "blah");
    StringEntity se = new StringEntity( "JSON: " + json.toString());
    se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    post.setEntity(se);
    response = client.execute(post);
} catch(Exception e){
  e.printStackTrace();
}

我想要一些类似的东西

assertTrue(myRequestJSON.matches("blah"));

但我似乎无法使用里面的任何东西来获得它

Robolectric.getFakeHttpLayer().getLastSentHttpRequestInfo();

...或任何其他变体。

帮助?

顺便说一句,如果您认为我的测试方法被误导,我当然愿意以不同的方式思考这个问题。

谢谢!

编辑:我意识到我的虚拟代码中有“myResponseJSON”而不是“myRequestJSON”,这可能使它不清楚 - 已修复。

4

1 回答 1

2

我之前的解决方案完全错了。你可以很简单地做到这一点,它会出现。我在 Robolectric 示例代码中找到了解决方案(可以预见):

HttpPost sentHttpRequest = (HttpPost) Robolectric.getSentHttpRequest(0);
StringEntity entity = (StringEntity) sentHttpRequest.getEntity();
String sentPostBody = fromStream(entity.getContent());
assertThat(sentPostBody, equalTo("a post body"));
assertThat(entity.getContentType().getValue(), equalTo("text/plain; charset=UTF-8"));

(从这里

于 2013-02-01T09:53:12.033 回答