Integration testing of JAX-RS services

Viewed 5004

I recently implemented simple JAX-RS REST endpoint. I'm wondering is there any transparent way of integration testing?

I searched a bit on stackowerflow and found these questions: first, second. They are a bit outdated and I hope there is already some better way of testing. The solutions proposed there don't solve my problem as they provide either vendor-specific or some complex third party ways.

Q: What is the modern way of testing JAX-RS services? Does Java EE provide solution for that? Or generally what is the best way of writing controller tests in Java EE ecosystem?

To be more specific I'm looking for some way that allows to easily test a REST call. In spring framework it usually looks like this:

@Autowired
MockMvc mvc;
@MockBean
MyService service;

@Test
public void shouldGetMyDto() {
    MyDto dto = new MyDto("test-id", "test-name");
    given(service.getMyDto("test-id")).willReturn(dto);

    mvc.perform(get("/api/my-entities/test-id"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(APPLICATION_JSON_UTF8_VALUE))
            .andExpect(jsonPath("$.id", is("test-id")))
            .andExpect(jsonPath("$.name", is("test-name")));

    verify(service).getMyDto("test-id");
}
1 Answers

Arquillian and CDI Alternatives

For Java EE, you could use Arquillian to create micro deployments for your tests, allowing you to pick the classes you want to deploy. You can use CDI alternatives to provide a mock implementation for your services.

To add Maven dependencies to an Arquillian deployment, refer to this answer.

JAX-RS Client API and REST Assured

For testing the REST API itself, you can rely on the JAX-RS Client API, introduced in JAX-RS 2.0.

If you prefer a fluent API similar to what Spring provides, go for REST Assured.

Exploring other approaches

Depending on your needs regarding tests, you could also explore other solutions that do not use Java.

For example, Postman allows you to write test scripts. And it also provides Newman, to run the collections from the command line with Node.js.

Related