我正在嘗試測驗我的控制器@WithMockUser用于模擬身份驗證的方法安全性。
關鍵是在我的應用中有 3 個角色(我們稱它們為 Role_1、Role_2 和 Role_3),我想分別測驗它們。
現在,我必須撰寫 3 個不同的測驗來實作這個目的,如下所示:
@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)
}
但我想對角色 1,2 進行引數化,因為它們是完全相同的測驗。這些方式我會有這樣的事情:
@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)
}
uj5u.com熱心網友回復:
跳過@WithMockUser并通過 以編程方式為您的請求設定角色SecurityMockMvcRequestPostProcessors.user("myUser").roles("ADMIN")。
然后,您可以與此類似地引數化您的測驗:
fun runAndAssert(user: String, role: String, statusMatcher: ResultMatcher){
this.mockMvc
.perform(get("/url/").with(user(user).roles(role)))
.andExpect(statusMatcher)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/475594.html
上一篇:Excel宏將某些字符插入列
下一篇:如何使用JPA連接兩個表?
