Search code examples
spring-bootspring-securityreflectionjunit5

Is it possible to has more than 1 @WithMockUser in one test method?


I am using Spring boot + Spring Security + Junit 5, latest version.

Is it possible that in one testing method, I can use two @WithMockUser() ? So the testing method run two times and each time with different @WithMockUser information? For example, I have

@WithMockUser(username="admin",roles={"USER","ADMIN"})
@WithMockUser(username="user" ,roles={"USER","ADMIN"})
public void test1() {}

Equals run two times. like:

@WithMockUser(username="admin",roles={"USER","ADMIN"})
public void test1() {}

and

@WithMockUser(username="user" ,roles={"USER","ADMIN"})
public void test1() {}

Java source code solution


Solution

  • You can use UserRequestPostProcessor to configure MockMvc request to achieve the equivalent behaviour of @WithMockUser.

    Together with Junit5 's parameterised test , you can do something like :

    import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
    import static org.junit.jupiter.params.provider.Arguments.of;
    
    
    @ParameterizedTest
    @MethodSource("withMockUser")
    void someTest(String username, String[] roles) throws Exception {
    
        mockMvc.perform(get("/foo")         
               .with(user(username).roles(roles)))
               .......
    }
    
    private static Stream<Arguments> withMockUser() {
        return Stream.of(
                of("admin", new String[]{"USER", "ADMIN"}),
                of("user", new String[]{"USER", "ADMIN"})
        );
    }