I have several unit tests that use Squares OkHttp
s 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!
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With