我有一段我要测试的代码,它接受一个JSON字符串并使用JSON字符串中的对象来调用方法
@RequestMapping(value = "/cancel", method = RequestMethod.POST, produces = "application/json")
public ReservationCancelResponseType cancel(@RequestBody CancelReservationRequest request) {
ReservationCancelResponseType result = null;
for(BrandEnum brand : request.getBrands()) {
switch(brand) {
case BRAND_NAME:
result = service.cancel(request);
break;
}
}
return result;
}
我试图使用以下代码来调用它
@Test
public void testCancel() throws Exception {
ReservationCancelResponseType responseType = new ReservationCancelResponseType();
CancelReservationRequest request = new CancelReservationRequest();
List<BrandEnum> brands = new ArrayList<>();
brands.add(BrandEnum.BRAND_NAME);
request.setBrands(brands);
String requestString = objectMapper.writeValueAsString(request);
when(service.cancel(request)).thenReturn(responseType);
this.mockMvc.perform(post("/cancel")
.contentType(MediaType.APPLICATION_JSON)
.content(requestString)
).andExpect(status().isOk());
}
我认为这不起作用的原因是因为在when().thenReturn()
调用中,我传入的是一个对象,但在其余的调用中,我传入了由此对象创建的String
版本objectMapper
所以这些不同,所以我null
来电when().thenReturn()
这是否正确?如果是这样,你会建议我如何解决这个问题?
答案 0 :(得分:1)
假设您的控制器在测试流程中使用的服务实例与您在测试中模拟的实例完全相同,那么问题的最可能原因是CancelReservationRequest
的{{1}的实现}}。当Mockito尝试将您的equals()
调用所期望的实例与控制器方法中使用的实例进行比较时,它没有equals()
或其equals()
实现返回false。
您可以通过更改...
来验证这一点when/then
......来:
when(service.cancel(request)).thenReturn(responseType)
如果when(service.cancel(Mockito.any(CancelReservationRequest.class))).thenReturn(responseType)
方法返回您的响应类型,那么您将知道问题与service.cancel()
的相等性检查有关。解决此问题的方法是实现CancelReservationRequest
方法,该方法允许Mockito正确比较equals()
调用所需的实例与控制器方法中使用的实例。如果创建自定义when/then
方法不是跑步者,您甚至可以使用Mockito.refEq()
。