Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 797
Vadym Roganin Avatar asked Dec 25 '13 13:12

Vadym Roganin


1 Answers

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());

}
like image 126
Vadym Roganin Avatar answered Oct 21 '22 01:10

Vadym Roganin