I'm trying to find some manual how to test POST
methods using jersey
framework, only got examples for GET
method.
Here's example:
@POST
@Path("add")
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public Response addUser(JAXBElement<User> user) {
int code = userService.addUser(user.getValue());
if (code == 500) {
return Response.status(500).build();
}
return Response.status(code).entity(user).build();
}
Could you please post some POST method test example? Thank you in advance.
After research I did it!
Here's my solution, it works just fine. And it's rather integration test, but we can write unit tests in similar manner.
public class RestTest extends JerseyTest{
@Override
protected Application configure() {
return new Your_Resource_Config(); //Your resource config with registered classes
}
//@Before and/or @After for db preparing etc. - if you want integration tests
@Test
public void addUserTest() {
User user = new User();
user.setEmail("[email protected]");
user.setName("Jane Doe");
user.getUserRoles().getRoles().add("supertester");
Entity<User> userEntity = Entity.entity(user, MediaType.APPLICATION_XML_TYPE);
target("users/add").request().post(userEntity); //Here we send POST request
Response response = target("users/find").queryParam("email", "[email protected]").request().get(); //Here we send GET request for retrieving results
Assert.assertEquals("[email protected]", response.readEntity(User.class).getEmail());
}
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