VanDavv
VanDavv

Reputation: 836

How to post a JSON request in Jersey-Test

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?

Upvotes: 6

Views: 4264

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 209002

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.

Upvotes: 6

Related Questions