首页 > 解决方案 > 具有真实服务实现的 WebMvcTest

问题描述

如何在 Spring Boot 中创建“准”MVC 集成测试。我想使用我真正的服务实现,但我做不到。我怎样才能注入真正的实现而不是模拟。我的课看起来像这样

@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";
    }
}

和测试

@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());
    }

}

标签: javaspringspring-bootmockmvc

解决方案


通常 WebMvcTest 不会创建一个包含所有组件(服务等)注入的完整 Spring 上下文,而只会创建您定义的控制器。要么使用完整的 SpringBootTest,要么在 WebMvcTest 类中添加类似的内容:

@TestConfiguration
static class AdditionalTestConfig {
    @Bean
    public RolesManagerService getService() {
        return new RolesManagerService();
    }
}

推荐阅读