Vadym Roganin Vadym Roganin - 3 months ago 21
reST (reStructuredText) Question

Jersey Test Framework 2.5 - test POST method

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.

Answer

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("user2@mail.com");
    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", "user2@mail.com").request().get(); //Here we send GET request for retrieving results
    Assert.assertEquals("user2@mail.com", response.readEntity(User.class).getEmail());

}
Comments