I'm writing unit test for my REST application, and i'm stuck. When i used header parameters, tests were obvious. But now, my requests are in JSON, and i dont know how to test it. Maybe there is a way to do it with Jersey or maybe with Jackson. My line where i get the response from my resource looks like this:
final Response response = RULE.getJerseyTest().target("/actors/1").request().post(/* json request */);
Where the RULE is ResourceTestRule.
What should i do with it to make it POST a resource?
Jersey endpoints and return a JSON responseCreate a few endpoints in Jersey, and Jackson will handle the object from/to JSON conversion. 4.1 Create the following endpoints and return JSON response. GET /json/ , returns a JSON string. GET /json/{name} , returns an User object containg the {name} in JSON string.
Jersey JSON support comes as a set of JAX-RS MessageBodyReader<T> and MessageBodyWriter<T> providers distributed with jersey-json module. These providers enable using three basic approaches when working with JSON format: POJO support. JAXB based JSON support.
Jersey uses Jackson internally to convert Java objects to JSON and vice versa.
Once you call request()
on the WebTarget
(target("/actors/1")
), you get back an Invocation.Builder
, which extends SyncInvoker
. If you look at all the post()
methods on the SyncInvoker
, you will see that they all take Entity
Response post(Entity<?> entity)
<T> T post(Entity<?> entity, Class<T> responseType)
<T> T post(Entity<?> entity, GenericType<T> responseType)
If you look at the Entity
class, you will just see a bunch of static methods like form
, html
, json
, xml
, text
. Just pass in your entity (JSON POJO) to the json
method to create an Entity
of type application/json
.
...request().post(Entity.json(yourPojo));
You should go through all the javadoc links I provided to get familiar with the APIs, at least so you know what's going on behind all those chained method calls.
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