I try to create my first the test for a simple spring-boot controller but I get Handler: Type = null
. In browser code is work but a test fails. My App use spring-security. Please help me fix it an issue and understand my mistake. Thank You.
This is controller:
private final ItemService service;
@GetMapping("/get_all_items")
public String getAllItems(Model model) {
model.addAttribute("items", service.getAll());
return "all_items";
}
This is a test.
@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()
);
}
}
This is result log:
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