Why spring test is fail, does not work @MockBean

Pavel picture Pavel · Aug 27, 2017 · Viewed 10.5k times · Source

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

Answer

Sam Brannen picture Sam Brannen · Aug 28, 2017

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