我想模拟Order数组类Order []。class。下面的MockMapper读取Order []。class并需要返回Order []。class。
服务等级
public class OrdersConnectorImpl {
public Order getOrderById(String Id, OrderType orderType) throws Exception {
Response response = null;
response = orderServiceTarget.queryParam("ID", Id).queryParam(ORDER_TYPE, orderType).request().accept(MediaType.APPLICATION_JSON)
.get();
final StatusType responseStatus = response.getStatusInfo();
final String serverResponseStr = response.readEntity(String.class);
if (responseStatus.equals(Response.Status.OK)) {
objectMapper = getObjectMapper(); // we have a private method in this class
Order[] orders = objectMapper.readValue(serverResponseStr, Order[].class);
if(orders.length>0) {
return orders[0];
}
}
}
}
测试类
public class OrdersConnectorImplTest {
private ObjectMapper mockMapper;
private class MockOrdersConnectorImpl extends OrdersConnectorImpl {
@Override
protected ObjectMapper getObjectMapper() {
return mockMapper;
}
}
}
@Test
public void test_getRenewalOrderForContract() throws Exception {
Response mockResponse = mock(javax.ws.rs.core.Response.class);
Order mockOrder = mock(Order.class);
when(mockResponse.getStatusInfo()).thenReturn(Status.OK);
when(mockResponse.readEntity(String.class)).thenReturn("{}");
when(mockBuilder.get()).thenReturn(mockResponse);
when(mockMapper.readValue("{}", Order[].class)).thenReturn(mockOrder); // this is the problem line
orderConnector.getOrderById("id", OrderType.NEW);
}
}
请在这里更正我该如何返回期望值。
答案 0 :(得分:0)
您已经自动连接了mockMapper
,这意味着将注入ObjectMapper的实际对象。
在when
部分中,您将设置嘲讽MapperMapper的行为,
编辑1
在您的情况下,无需模拟Order类,您必须返回可以在测试中创建的Order数组。 仅供参考,使用Junit是不可能的,您可以模拟在方法内部创建的对象。