Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I verify the content of a POST Body with MockWebServer?

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!

like image 676
ASP Avatar asked Jul 22 '16 06:07

ASP


Video Answer


1 Answers

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"));
like image 99
Jesse Wilson Avatar answered Sep 28 '22 07:09

Jesse Wilson