Description
Summary
Quite some Mock-Mvc requests configuration could be automatized. Additionally, The framework could provide with finer grained MockHttpServletRequestBuilder
factories and even shortcuts to issue MockMvc requests in one call.
Most of these is not security related and if this request is ever accepted, you might split what is pure security from what is just MVC related (every-thing but Authorization header). But as security is involved and the solution I propose is part of set of OAuth2 unit testing improvements I request, here it is...
Actual Behavior
Content-type, Accept and Authorization headers are to be manually added to each MockMvc request. This is boring and error-prone (you can easily forget Authorization header or miss-match Content-type and actual body serialization mechanism).
Expected Behavior
As done in MockMvcHelper
and OAuth2MockMvcHelper
:
- Authorization header set when OAuth2 authentication is configured (test decorated with authentication meta-data)
- Content-Type header set for each POST, PUT and PATCH request
- Accept header set for each GET, POST and OPTION request
linked requests
- Ease controllers unit tests in OAuth2 secured apps #6557
- @WithMockUser alike annotations for OAuth2 #6558
- Have unit test OAuth2 authentication configured with annotations #6559
Sample
Overall result in controller unit tests:
@WebMvcTest(UserController.class)
@Import({ResourceServerConfig.class})
@EnableSpringDataWebSupport
public class UserControllerTest extends OAuth2ControllerTest {
@MockBean
UserRepository userRepo;
@Test
@WithMockOAuth2User(user = @WithMockUser(username = "admin", authorities = "READ_USERS"))
public void whenAuthenticatedWithReadUserPrivilegeThenListUsersReturnsUsersPage() throws Exception {
final List<User> users = Arrays.asList(admin, user);
when(userRepo.findAll(any(Pageable.class))).thenAnswer(invocation ->
new PageImpl<>(users, (Pageable) invocation.getArguments()[0], users.size()));
api.get("/users/")
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.elements", hasSize(users.size())))
.andDo(document("users-collection",
ignorePage(responseFields(), "elements"),
links()));
}
}
In this sample:
api
is aMockMvc
wrapper instance- Authorization and Accept headers are transparently added
MockHttpServletRequestBuilder
is created, configured, build and performed in one call- you can browse my source for additional samples involving further request builder configuration (cookies or additional headers)
P.S.
SerializationHelper
, used in MockMvcHelper
, quite eases requests body serializing using registered message converters. It might be worth being contributed to the framework too but don't quite know where...