我有一个类将 POJO 发布到外部 API。我想测试这个方法。
public int sendRequest(Event event) {
Client client = ClientBuilder.newClient();
WebTarget baseTarget = client.target(some url);
Invocation.Builder builder = baseTarget.request();
Response response = builder.post(Entity.entity(event, MediaType.APPLICATION_JSON));
int statusCode = response.getStatus();
String type = response.getHeaderString("Content-Type");
if (Status.Family.SUCCESSFUL == Status.Family.familyOf(statusCode)) {
m_log.debug("The event was successfully processed by t API %s", event);
}
else if (Status.Family.CLIENT_ERROR == Status.Family.familyOf(statusCode)) {
m_log.error("Status code : <%s> The request was not successfully processed by API. %s", statusCode, event);
}
return statusCode;
}
我写了一个这样的单元测试
@Test
public void sendRequest_postAuditEvent_returnOK() {
int statusCode = EventProcessor.sendRequest(event);
assertEquals(Status.OK.getStatusCode(), statusCode);
}
但这会向 API 发送一个真实的请求。我是 Mockito 的新手。谁能帮我模拟这个请求?
编辑:
@Mock Client m_client;
@Mock WebTarget m_webTarget;
@Mock Invocation.Builder m_builder;
@Mock Response m_response;
@Test
public void sendRequest_postAuditEvent_returnOK() {
when(m_client.target(anyString())).thenReturn(m_webTarget);
when(m_webTarget.request()).thenReturn(m_builder);
when(m_builder.post(Entity.entity(m_AuditEvent, MediaType.APPLICATION_JSON))).thenReturn(m_response);
when(m_response.getStatus()).thenReturn(Response.Status.BAD_REQUEST.getStatusCode());
assertEquals(Status.BAD_REQUEST.getStatusCode(), m_AuditEventProcessor.sendRequest(m_AuditEvent));
}
我尝试模拟这些方法,但它不起作用。仍然调用真正的方法。
梦里花落0921
ibeautiful
相关分类