我正在尝试对REST服务进行模拟测试,该服务将数据更新到给定Id的数据库中。
我尝试过Add(POST请求),它运行良好。
但当我尝试PUT请求时,它会给我一个错误:
Argument(s) are different! Wanted:
service.updateMet(
Met [id=10, name=mnTest, definition=mdTest]
);
-> at org.MetApp.MetTest.updateMet(MetTest.java:175)
Actual invocation has different arguments:
service.updateMet(
Met [id=10, name=mnTest, definition=mdTest]
);
以下是代码:
@Test
public void updateMet() throws Exception {
String cName = "mae";
MetInDTO metDTO = new MetInDTO();
metDTO.setName("mnTest");
metDTO.setDescription("mdTest");
DataTerm dTerm = new DataTerm(10, metDTO.getName(), metDTO.getDescription());
Met met = new Met(dTerm);
Mockito.doNothing().when(service).updateMet(met);
mockMvc.perform(put("/restapi/{cname}/met/{id}", cName, met.getId())
.contentType(contentType).content(convertObjectToByte(metDTO)))
.andExpect(status().isOk());
verify(service, times(1)).updateMet(met);
}
更新:
@Test
public void updateMet() throws Exception {
String cName = "mae";
MetInDTO metDTO = new MetInDTO();
metDTO.setName("mnTest");
metDTO.setDescription("mdTest");
DataTerm dTerm = new DataTerm(10, metDTO.getName(), metDTO.getDescription());
Met met = new Met(dTerm);
final ArgumentCaptor<Met> captor = ArgumentCaptor.forClass(Met.class);
Mockito.doNothing().when(service).updateMet(any(Met.class));
mockMvc.perform(put("/restapi/{cname}/met/{id}", cName, met.getId())
.contentType(contentType).content(convertObjectToByte(metDTO)))
.andExpect(status().isOk());
verify(service).updateMet(captor.capture());
Met captured = captor.getValue();
assertEquals(met.getName(), captured.getName());
assertEquals(met.getDefinition(), captured.getDefinition());
}
由于您无法覆盖Met
类的equals()方法,因此您可以选择捕获监视的service
的输出,并检查它是否与您想要的相匹配。你可以这样做:
doNothing().when(service).updateMet(any(Met.class));
final ArgumentCaptor<Met> captor = ArgumentCaptor.forClass(Met.class);
mockMvc.perform(bla, bla);
verify(service).updateMet(captor.capture());
final Met captured = captor.getValue();
// verify captured Met instance here
注意:对于断言,您可能需要使用assertj。
是否覆盖Met
的equals()
方法?arg列表是相同的(在第一个片段中),但它表明您使用了不同的参数。