我試着創建我的第一個測試簡單的彈簧引導控制器,但我得到Handler: Type = null
。在瀏覽器中,代碼是可行的,但測試失敗。我的應用程序使用spring-security。請幫我解決一個問題並理解我的錯誤。謝謝。爲什麼春季測試失敗,不起作用@MockBean
這是控制器:
private final ItemService service;
@GetMapping("/get_all_items")
public String getAllItems(Model model) {
model.addAttribute("items", service.getAll());
return "all_items";
}
這是一個測試。
@RunWith(SpringRunner.class)
@WebMvcTest(ItemController.class)
public class ItemControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private ItemService itemService;
@Test
@WithMockUser(username = "user", roles = "user")//mock security.
public void whenGetAllItemsThenControllerReturnAllItems() throws Exception {
given(
itemService.getAll()
).willReturn(
new ArrayList<Item>()
);
mvc.perform(
get("/get_all_items").accept(MediaType.TEXT_HTML)
).andExpect(
status().isOk()
);
}
}
這是結果日誌:
MockHttpServletRequest: HTTP Method = GET Request URI = /get_all_items Parameters = {} Headers = {Accept=[text/html]}
Handler: Type = null
Async: Async started = false Async result = null
Resolved Exception: Type = null
ModelAndView: View name = null View = null Model = null
FlashMap: Attributes = null
MockHttpServletResponse: Status = 403 Error message = Access is denied Headers = {X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY], Strict-Transport-Security=[max-age=31536000 ; includeSubDomains]} Content type = null Body = Forwarded URL = null Redirected URL = null Cookies = []
java.lang.AssertionError: Status Expected :200 Actual :403
您是否嘗試過'@ MockMvc'?有一些變化嗎? – Reborn
錯誤就在那裏。 ':狀態= 403錯誤消息=訪問被拒絕標題。您需要提供安全聲明,或者禁用它以進行單元測試。 –
@Darren Forsythe是的,但我使用'@WithMockUser(username =「user」,roles =「user」)'這是不夠的?如何實施提供安全信用?我想我的@WithMockUser解決。 – Pavel