3

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

Pavel
  • 2,005
  • 5
  • 36
  • 68
  • Have you tried `@MockMvc`? Is there some changes? – Malakai Aug 27 '17 at 13:46
  • The error is right there. `: Status = 403 Error message = Access is denied Header`. You need to provide security creds, or disable it for the unit-testing. – Darren Forsythe Aug 27 '17 at 13:50
  • @Darren Forsythe Yes but I use `@WithMockUser(username = "user", roles = "user")` it's not enough? How to implement provide security creds? I think my @WithMockUser solve. – Pavel Aug 27 '17 at 14:04
  • @Reborn I try to replace `@Autowired` to `@MockMvc` after You're a comment but my IDE get the warning message about constructor. – Pavel Aug 27 '17 at 14:08

1 Answers1

4

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

Sam Brannen
  • 29,611
  • 5
  • 104
  • 136
  • my mistake @WithMockUser(username = "user", roles = "user") ->@WithMockUser(username = "user", roles = "USER") need convert role "user" too CAPSLOOK. And all ok. – Pavel Aug 28 '17 at 18:41