rewrite-spring
rewrite-spring copied to clipboard
Migrate MockMvc Hamcrest assertions over to AssertJ
What problem are you trying to solve?
Spring Boot 3.4 added a more fluent way to write MockMvc assertions using AssertJ.
What precondition(s) should be checked before applying this recipe?
Using Hamcrest assertions.
Describe the situation before applying the recipe
// static import of MockMvcRequestBuilders.* and MockMvcResultMatchers.*
mockMvc.perform(get("/accounts/1")).andExpectAll(
status().isOk(),
content().contentType("application/json;charset=UTF-8"));
Describe the situation after applying the recipe
assertThat(mockMvc.get().uri("/hotels/{id}", 42))
.hasStatusOk()
.hasContentTypeCompatibleWith(MediaType.APPLICATION_JSON);
Have you considered any alternatives or workarounds?
There is also the form of mockMvc.perform to reuse more of the original request, while still using fluent assertions:
https://docs.spring.io/spring-framework/reference/testing/mockmvc/assertj/integration.html
// Static import on MockMvcRequestBuilders.get
assertThat(mockMvc.perform(get("/hotels/{id}", 42)))
.hasStatusOk();
// For custom matchers
// Static import on MockMvcResultMatchers.status
assertThat(mockMvc.get().uri("/hotels/{id}", 42))
.matches(status().isOk());
This is likely not preferred as it still requires additional static imports, but could be an option for some cases, or as an intermediate to migrate to before moving over completely.
Any additional context
- https://docs.spring.io/spring-framework/reference/testing/mockmvc/setup-options.html
- https://docs.spring.io/spring-framework/reference/testing/mockmvc/assertj.html
- https://docs.spring.io/spring-framework/reference/testing/mockmvc/assertj/integration.html