Skip to content

Have unit test OAuth2 authentication configured with annotations #6559

@ch4mpy

Description

@ch4mpy

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

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions