Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

java - WebMvcTest with real service implementation

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

}
question from:https://stackoverflow.com/questions/66058439/webmvctest-with-real-service-implementation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...