-
Notifications
You must be signed in to change notification settings - Fork 6.1k
Closed
Description
Summary
Default token store has no knowledge of test configured authentication
Actual Behavior
OAuth2Athentication is anonymous, whatever I try to configure it with @WithMockUser or alike
Expected Behavior
When a test is decorated with authentication meta-data, OAuth2Athentication should be set-up accordingly
linked requests
- Ease controllers unit tests in OAuth2 secured apps #6557
- @WithMockUser alike annotations for OAuth2 #6558
- reduce controllers unit tests boiler-plate code #6560
As mentioned in other requests, I ended with a solution involving a parent class for all my controllers unit tests, which mocks TokenStore so that it recognizes a specific Authorization header and creates OAuth2Authorization according to what is configured with @WithMockOAuth2Client
and @WithMockOAuth2User
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()));
}
}
Metadata
Metadata
Assignees
Labels
No labels