webmvctest与真正的服务实现

np8igboo  于 2021-07-24  发布在  Java
关注(0)|答案(0)|浏览(203)

如何在springboot中创建“准”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());
    }

}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题