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");
}
Integration testing is performed using the black box method. This method implies that a testing team interacts with an app and its units via the user interface – by clicking on buttons and links, scrolling, swiping, etc. They don't need to know how code works or consider the backend part of the components.
In simple terms, Wiremock is a mocking setup for integration tests. It's simply a mock server that is highly configurable to return an expected response for a given request.
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.
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.
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.
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