Mockito在put请求中给出错误

时间:2015-02-27 06:48:31

标签: java spring mockito

我正在尝试进行REST服务的模拟测试,将数据更新为给定Id的数据库。

我尝试过可以正常工作的添加(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());
}

2 个答案:

答案 0 :(得分:2)

由于您无法覆盖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

答案 1 :(得分:0)

您是否覆盖equals()的{​​{1}}方法? arg列表是相同的(在第一个片段中),但它表示你正在使用不同的参数。