本章提供一个简单的 Mock 测试例子作为参考

pom.xml 引入测试

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-test</artifactId>
  4. </dependency>

待测试的 Controller

  1. /**
  2. * 试卷
  3. *
  4. * @author yinjianwei
  5. * @date 2017/12/07
  6. */
  7. @RestController
  8. @RequestMapping(value = "/exam")
  9. public class ExamController {
  10. private final static Logger logger = LoggerFactory.getLogger(ExamController.class);
  11. @Autowired
  12. private ExamService examService;
  13. /**
  14. * 根据条件筛选试卷数据
  15. *
  16. * @param examQuery 查询条件
  17. * @return
  18. */
  19. @RequestMapping("/list_exam_by_condition")
  20. public Result listExamByCondition(ExamQuery examQuery) {
  21. Result result = null;
  22. try {
  23. List<ExamVO> examVOs = examService.listExamByCondition(examQuery);
  24. result = Result.ok(examVOs);
  25. } catch (ServiceException e) {
  26. logger.error("根据条件筛选试卷数据,报错信息如下:", e);
  27. result = Result.result(e.getErrorCode(), e.getMessage());
  28. }
  29. return result;
  30. }
  31. }

测试类

  1. /**
  2. * 试卷测试类
  3. *
  4. * @author yinjianwei
  5. * @date 2018/07/16
  6. */
  7. @RunWith(SpringRunner.class)
  8. @SpringBootTest(classes = Application.class)
  9. public class ExamControllerTest {
  10. @Autowired
  11. private ExamController examController;
  12. private MockMvc mockMvc;
  13. @Before
  14. public void befor() {
  15. this.mockMvc = MockMvcBuilders.standaloneSetup(examController).build();
  16. }
  17. @Test
  18. public void listExamByCondition() throws Exception {
  19. MvcResult mvcResult = mockMvc
  20. .perform(MockMvcRequestBuilders
  21. .get("/exam/list_exam_by_condition")
  22. .accept(MediaType.APPLICATION_JSON)
  23. .param("name", "二"))
  24. .andExpect(MockMvcResultMatchers.status().isOk())
  25. .andDo(MockMvcResultHandlers.print()).andReturn();
  26. System.out.println("***************************");
  27. System.out.println("输出:" + mvcResult.getResponse().getContentAsString());
  28. System.out.println("***************************");
  29. }
  30. }

注意: @SpringBootTest(classes = Application.class),classes 属性建议配置,否则可能出现找不到启动类的错误,测试执行不下去。