Home > Net >  Parametrize @WithMockUser Spring boot
Parametrize @WithMockUser Spring boot

Time:05-16

i'm trying to test the method security of my controller using @WithMockUser to mock the authentication.

The point is that in my app there are 3 roles (Let's call them Role_1, Role_2 and Role_3) and i would like to test them separately.

Right now, i have to write 3 different tests to achieve this purpose, like this:

@Test
@WithMockUser(roles = ["1"])
fun `Role 1 should receive 403 Status code`(){
    val url = "$debtorsPath/"
    this.mockMvc
        .perform(get("/url/"))
        .andExpect(status().isUnauthorized)
}

@Test
@WithMockUser(roles = ["2"])
fun `Role 2 should receive 403 Status code`(){
    this.mockMvc
        .perform(get("/url/"))
        .andExpect(status().isUnauthorized)
}

@Test
@WithMockUser(roles = ["3"])
fun `Role 3 should receive 200 Status code`(){
    this.mockMvc
        .perform(get("/url/"))
        .andExpect(status().isOk)
}

But i would like to parametrize the roles 1,2 since they're exactly the same test. These way i would have something like this:

@Test
@ParameterizedRoles(values = ["1", "2"])
fun `Roles 1 & 2 should receive 403 Status code`(){
    val url = "$debtorsPath/"
    this.mockMvc
        .perform(get("/url/"))
        .andExpect(status().isUnauthorized)
}

CodePudding user response:

Skip @WithMockUser and just set the role programmatically for your request via SecurityMockMvcRequestPostProcessors.user("myUser").roles("ADMIN").
You can then parameterize your test similarly to this:

fun runAndAssert(user: String, role: String, statusMatcher: ResultMatcher){
    this.mockMvc
        .perform(get("/url/").with(user(user).roles(role)))
        .andExpect(statusMatcher)
}
  • Related