我有一个类将 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;@Testpublic 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));}我尝试模拟这些方法,但它不起作用。仍然调用真正的方法。
2 回答
梦里花落0921
TA贡献1772条经验 获得超6个赞
理想情况下,该类应该Client在其构造函数中使用 a ,这样您就可以在测试时用模拟替换真实的客户端实例。
class EventProcessor {
private Client client;
public EventProcessor(Client client) {
this.client = client;
}
public int sendRequest(Event event) {
WebTarget baseTarget = client.target(some url);
...
}
}
ibeautiful
TA贡献1993条经验 获得超5个赞
您可以像这篇文章一样使用 powerMockito Mocking static methods with Mockito
如果你可以模拟这个返回的对象 ClientBuilder.newClient() 你可以模拟调用链中的所有其他对象。
PowerMockito.mockStatic(ClientBuilder.class);
BDDMockito.given(ClientBuilder.newClient(...)).willReturn([a Mockito.mock()...]);
添加回答
举报
0/150
提交
取消