18

I have several unit tests that use Squares OkHttps MockWebServer. The tests run all fine, and everything works very well. The one thing I couldn't do so far is to verify the content of the POST requests.

Why do I want to do that?
The REST Api I'm developing against has some methods, that require the data objects to be sent in the POST requests body, other methods require the objects to be sent as a FormUrlEncoded data field. So I want to ensure, that the Retrofit interface was set up correctly acc. to the spec.

The following unit test will pass, but the first one sends the data incorrectly inside the body:

//Incorrect
@POST("api/v1/user/senddata")
Observable<Void> senddata (
        @Path("VIN") String vin,
        @Body PoiWrapper wrappedPoi);

//Correct
@FormUrlEncoded
@POST("api/v1/user/senddata")
Observable<Void> senddata(
        @Path("VIN") String vin,
        @Field("data") PoiWrapper wrappedPoi);

I know the MockWebServer has the takeRequest() method, but I'm stuck with getting the actual field and data from that requests body.

Thank you for your help!

ASP
  • 773
  • 1
  • 8
  • 22

1 Answers1

34

Try following these examples:

RecordedRequest recordedRequest = server.takeRequest();
assertEquals("POST", recordedRequest.getMethod());
assertEquals("def", recordedRequest.getBody().readUtf8());
assertEquals("3", recordedRequest.getHeader("Content-Length"));
assertEquals("text/plain; charset=utf-8", recordedRequest.getHeader("Content-Type"));
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Jesse Wilson
  • 39,078
  • 8
  • 121
  • 128
  • 7
    Ok, that's not 100% the solution to my problem, but it pushed me into the right direction. The `readUtf8()` returns the body with HTML encoded form fields. I still have to decode the String, deserialize it to a `Map` and then check the keys and values. – ASP Jul 25 '16 at 11:45
  • 1
    @ASP, what was the approach taken to finally decode the String? Could you please share the code snippet here? – pixelWorld May 18 '22 at 07:51
  • @pixelWorld Sorry, this was 6 years ago. I don't have access to this code anymore. – ASP Aug 10 '22 at 08:45