Mock测试属于一种特殊的测试场景,在开发的过程中,可能由于协同开发的原因,自己需要测试自己开发的业务,但是业务中又依赖了同事开发的一些功能。按照正常的测试逻辑,可能会出现无法正常的完成测试需求,甚至代码都无法执行,此时就可以使用Mock测试的方法方法。 Mock测试的原理大致为:如果测试的方法依赖未知的对象时,可以通过Mock去抽象这个未知的对象,并对未知的对象的方法进行抽象返回我们想要的数据,以供我们的测试使用。以此完成我们的方法测试需求。 Spring Boot的测试模块支持Mock测试和junit测试。因此我们在SpringBoot开发时,可以在引入了Springboot测试模块后直接享受Mock测试和Junit单元测试带来的便利。
@SpringBootTest @RunWith(SpringRunner.class) publicclassCarServiceTest{ @Autowired public CarService carService;
@Test @Rollback @Transactional publicvoidtestAdd(){ Car car = new Car(); car.setType("SUV"); car.setName("BMW"); car = carService.add(car); System.out.println(car); } }
@SneakyThrows @Test publicvoidtestAddCar(){ //测试添加CarController 的addCar接口,使用MockBean模拟的CarService的Bean Car car = new Car(); car.setId(111L); car.setName("BYD"); car.setType("SUV"); Car car1 = new Car(); //期望调用addCar方法传入一个car1返回一个car的对象,对象的数据为 id=111L,name=BYD, type=SUV Mockito.when(carService.add(car1)).thenReturn(car);
String json = "{}";
mockMvc.perform(post("/car/").accept(MediaType.APPLICATION_JSON_VALUE).content(json).contentType(MediaType.APPLICATION_JSON_VALUE)) .andDo(MockMvcResultHandlers.print()); //执行结果: /** * MockHttpServletRequest: * HTTP Method = POST * Request URI = /car/ * Parameters = {} * Headers = [Content-Type:"application/json", Accept:"application/json", Content-Length:"2"] * Body = <no character encoding set> * Session Attrs = {} * * Handler: * Type = com.yiyi.controller.CarController * Method = com.yiyi.controller.CarController#add(Car) * * Async: * Async started = false * Async result = null * * Resolved Exception: * Type = null * * ModelAndView: * View name = null * View = null * Model = null * * FlashMap: * Attributes = null * * MockHttpServletResponse: * Status = 200 * Error message = null * Headers = [Content-Type:"application/json"] * Content type = application/json * Body = {"id":111,"name":"BYD","type":"SUV"} * Forwarded URL = null * Redirected URL = null * Cookies = [] */