Mockito使用参数测试REST方法

时间:2014-07-07 19:09:12

标签: java rest mockito

所以,我试图测试我的POST REST METHOD,它与Mokcito进行了争论:

@Test
public testRestAdd(){
RESTResource mockResource = Mockito.mock(RESTResource.class);
    String goodInput = "good input";
    Response mockOutput = null; //just for testing
    Mockito.when(RESTResource.addCustomer(Customer.class)).thenReturn(mockOutput);
}

REST呼叫是:

@POST
@Path("Add")
@Produces({MediaType.APPLICATION_JSON})
@Consumes(MediaType.APPLICATION_JSON)
 public Response addCustomer(final Customer CustomerTemp) throws Throwable {
//Code to add Customer
}

我在Mockito.when行收到错误,我提示addCustomer输入错误。有人可以告诉我这里我做错了什么吗?

1 个答案:

答案 0 :(得分:1)

在这一行:

Mockito.when(RESTResource.addCustomer(Customer.class)).thenReturn(mockOutput);

您调用addCustomer传递Customer类,而addCustomer方法应该接收Customer对象。如果你想为所有Cusotmer实例返回模拟,请使用Mockito的isA Matcher,如下所示:

Mockito.when(RESTResource.addCustomer(org.mockito.Matchers.isA(Customer.class))).thenReturn(mockOutput);

或者如果您真的不关心在addCustomer中收到哪个客户,您可以使用:

Mockito.when(RESTResource.addCustomer(org.mockito.Matchers.any())).thenReturn(mockOutput);