本章提供一个简单的 Mock 测试例子作为参考
pom.xml 引入测试
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
待测试的 Controller
/**
* 试卷
*
* @author yinjianwei
* @date 2017/12/07
*/
@RestController
@RequestMapping(value = "/exam")
public class ExamController {
private final static Logger logger = LoggerFactory.getLogger(ExamController.class);
@Autowired
private ExamService examService;
/**
* 根据条件筛选试卷数据
*
* @param examQuery 查询条件
* @return
*/
@RequestMapping("/list_exam_by_condition")
public Result listExamByCondition(ExamQuery examQuery) {
Result result = null;
try {
List<ExamVO> examVOs = examService.listExamByCondition(examQuery);
result = Result.ok(examVOs);
} catch (ServiceException e) {
logger.error("根据条件筛选试卷数据,报错信息如下:", e);
result = Result.result(e.getErrorCode(), e.getMessage());
}
return result;
}
}
测试类
/**
* 试卷测试类
*
* @author yinjianwei
* @date 2018/07/16
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class ExamControllerTest {
@Autowired
private ExamController examController;
private MockMvc mockMvc;
@Before
public void befor() {
this.mockMvc = MockMvcBuilders.standaloneSetup(examController).build();
}
@Test
public void listExamByCondition() throws Exception {
MvcResult mvcResult = mockMvc
.perform(MockMvcRequestBuilders
.get("/exam/list_exam_by_condition")
.accept(MediaType.APPLICATION_JSON)
.param("name", "二"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print()).andReturn();
System.out.println("***************************");
System.out.println("输出:" + mvcResult.getResponse().getContentAsString());
System.out.println("***************************");
}
}
注意: @SpringBootTest(classes = Application.class),classes 属性建议配置,否则可能出现找不到启动类的错误,测试执行不下去。