繁体   English   中英

如何使用Mockito在Jersey客户端中模拟请求?

[英]How to use Mockito to mock a request in Jersey client?

我有一个将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));
}

我尝试模拟方法,但是不起作用。 仍然调用真正的方法。

理想情况下,该类应在其构造函数中使用Client ,以便在测试它时可以用模拟代替真实的客户端实例。

class EventProcessor {
    private Client client;

    public EventProcessor(Client client) {
        this.client = client;
    }

    public int sendRequest(Event event) {
        WebTarget baseTarget = client.target(some url);
        ...
    }
}

您可以像本文中那样使用powerMockito与Mockito模拟静态方法

如果可以模拟此返回的对象ClientBuilder.newClient(),则可以模拟调用链中的所有其他对象。

PowerMockito.mockStatic(ClientBuilder.class);
BDDMockito.given(ClientBuilder.newClient(...)).willReturn([a Mockito.mock()...]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM