Why spring test is fail, does not work @MockBean

て烟熏妆下的殇ゞ 提交于 2019-12-10 20:56:42

问题


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


回答1:


This is essentially a duplicate question that has been answered here: https://stackoverflow.com/a/38676144/388980

The solution is to import the @Configuration class for your Spring Security configuration in addition to declaring @WebMvcTest(ItemController.class) like this @Import(SecurityConfig.class) (assuming your custom configuration for Spring Security is in a class named SecurityConfig).

You might also find the discussion in Spring Boot's issue tracker helpful as well: https://github.com/spring-projects/spring-boot/issues/6514

The other option is to disable Spring Security as explained here: Disable security for unit tests with spring boot



来源:https://stackoverflow.com/questions/45905591/why-spring-test-is-fail-does-not-work-mockbean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!