2

how can I create a "quasi" MVC integration test in Spring Boot. I would like to use my real implementation of a service, but I can't mange to do it. How can I inject real implementation instead of a mock. My classes look like this

@Controller
@RequiredArgsConstructor
public class DashboardController {

    private final RolesManagerService rolesManagerService;
    private final ServletRequestManagerService servletRequestManagerService;

    @GetMapping({"/", "/dashboard"})
    public String index(Model model, HttpServletRequest httpServletRequest) {
        model.addAttribute("canAddNewOrder", rolesManagerService.canRoleAccessApplicationPart(servletRequestManagerService.getRole(httpServletRequest), ApplicationPart.CREATE_NEW_ORDER));
        model.addAttribute("var", "test");
        return "dashboard";
    }
}

and the test

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = DashboardController.class)
@AutoConfigureMockMvc
class IndexControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private UserDetailsService userDetailsService;

    @MockBean
    RolesManagerService rolesManagerService;
    @MockBean
    private ServletRequestManagerService servletRequestManagerService;

    @Test
    void testDashboard() throws Exception {
        mockMvc.perform(get("/dashboard").with(user("admin").password("pass").roles("USER","ADMIN")))
                .andExpect(status().isOk())
                .andExpect(view().name("dashboard"))
                .andExpect(xpath("//a").nodeCount(1))
                .andExpect(model().attributeExists("canAddNewOrder"))
                .andExpect(model().size(2))
                .andExpect(model().attribute("var", equalTo("test")))
                .andExpect(model().attribute("canAddNewOrder", equalTo(false)))
                .andDo(print());
    }

}

1 Answer 1

2

Generally WebMvcTest will not create a full Spring context with all components (Service etc) injected, but only the Controller you define. Either use a full SpringBootTest, or add something like this in your WebMvcTest class:

@TestConfiguration
static class AdditionalTestConfig {
    @Bean
    public RolesManagerService getService() {
        return new RolesManagerService();
    }
}
2
  • 1
    key phrase is "in your WebMvcTest class", not just in same file. Great solution to a common problem
    – TimCO
    Mar 21 at 20:21
  • 1
    Very useful and resolved a similar problem for me. Thanks @Lars Westergren!
    – MiB
    Apr 25 at 11:41

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.