我正在嘗試對我的api進行單元測驗,這些api具有@PreAuthorize注解。我正在從Jwt中獲取cognito組,并將它們作為授權。我在api方法中的preauthorize注解中也進行了檢查。 更新:。 我得到了403 Forbidden錯誤
。測驗類:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status。
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = Config.class)
@SpringBootTest
@AutoConfigureMockMvc
public class TestStorageApis {
private MockMvc mockMvc;
@Test
@WithMockUser(authorities = {"admin"})
public void testDeleteCardProfile() throws Exception {
mockMvc.perform(MockMvcRequestBuilders)
.delete("/profile/{fileKey}","VOlUc3F5A_test.txt")
.andExpect(status().isOk())。
}
}
控制器方法:
@ApiResponses({ @ApiResponse(responseCode = "204", description = " Returns the delete success message"),
@ApiResponse(responseCode = "400", description = "Failed to delete file : Badrequest"),
@ApiResponse(responseCode = "404", description = "Failed to delete file, NotFound" ) })
@RequestMapping(value = "/profile/{fileKey}", consumes = MediaType.ALL_VALUE, method = { RequestMethod.DELETE })/span>
@PreAuthorize("hasAuthority('admin')")
public Mono< Boolean> deleteProfile(@AuthenticationPrincipal Jwt jwt, @PathVariable("fileKey") String fileKey) {
return storageService.removeProfile(fileKey)。
}
uj5u.com熱心網友回復:
錯誤資訊指出this.mockMvc是null。在你所分享的代碼中,你沒有在任何地方初始化this.mockMvc。
也許你的意思是要自動連接它
private MockMvc mockMvc。
uj5u.com熱心網友回復:
你所做的問題是mockMvc沒有被配置為在測驗期間與spring security一起作業。你目前的解決方案只處理了Method SecuritySee for clarification.
設定你的mockMvc正確,它應該作業。
@Before
public void setup {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build()。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/328077.html
標籤:
上一篇:使用Sinonjs的假池連接
