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

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

}

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


慕侠2389804
浏览 151回答 2
2回答

梦里花落0921

理想情况下,该类应该Client在其构造函数中使用 a ,这样您就可以在测试时用模拟替换真实的客户端实例。class EventProcessor {&nbsp; &nbsp; private Client client;&nbsp; &nbsp; public EventProcessor(Client client) {&nbsp; &nbsp; &nbsp; &nbsp; this.client = client;&nbsp; &nbsp; }&nbsp; &nbsp; public int sendRequest(Event event) {&nbsp; &nbsp; &nbsp; &nbsp; WebTarget baseTarget = client.target(some url);&nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; }}

ibeautiful

您可以像这篇文章一样使用 powerMockito Mocking static methods with Mockito如果你可以模拟这个返回的对象 ClientBuilder.newClient() 你可以模拟调用链中的所有其他对象。PowerMockito.mockStatic(ClientBuilder.class);BDDMockito.given(ClientBuilder.newClient(...)).willReturn([a Mockito.mock()...]);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java