之所以会出现错误,是因为使用
@MockBean(或
@Mock在非Spring环境中)使用Mockito模拟对象。该对象是您对象的空心代理。该代理具有与您的类相同的公共方法,默认情况下返回其返回类型的默认值(例如,对于对象为null,对于ints等为1),或者对于void方法不执行任何操作。
杰克逊抱怨,因为它必须序列化没有字段的代理,杰克逊也不知道该怎么办。
com.fasterxml.jackson.databind.exc.InvalidDefinitionException:未找到针对类org.mockito.internal.debugging.LocationImpl的序列化器,也未发现创建BeanSerializer的属性(为避免异常,请禁用SerializationFeature.FAIL_ON_EMPTY_BEANS
通常,当您模拟要测试的某个类的依赖项时,您将模拟它是用于测试的类的公共方法。直接返回您的依赖关系在现实世界中不是一个好用例-您不太可能必须编写这样的代码。
我想您正在尝试学习,所以让我提供一个改进的示例:
@RestControllerpublic class ReservationController { @Autowired private ReservationService reservationService; //my chnage here @RequestMapping(value = "/reservation", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.POST) @ResponseBody public Reservation getReservation() { return reservationService.getReservation(); //my chnage here }}通常,不是直接注入值对象,而是通常使用包含一些业务逻辑并返回某些内容的服务类-
在我的示例
ReservationService中
getReservation(),该类具有一个return和object类型的方法
Reservation。
有了它,您可以在测试中模拟
ReservationService。
@WebMvcTest@RunWith(SpringRunner.class)public class MvcTest { @Autowired private MockMvc mockMvc; @MockBean(name = "reservation") private ReservationService reservationService; //my chnage here @Test public void postReservation() throws Exception { // You need that to specify what should your mock return when getReservation() is called. Without it you will get null when(reservationService.getReservation()).thenReturn(new Reservation()); //my chnage here mockMvc.perform(MockMvcRequestBuilders.post("/reservation")) .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()); }}


