How to use Mockito to mock a request in Jersey client?











up vote
0
down vote

favorite












I have a class to post POJO to an external API. I want to test this method.



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;
}


I wrote a unit test like this



@Test
public void sendRequest_postAuditEvent_returnOK() {
int statusCode = EventProcessor.sendRequest(event);
assertEquals(Status.OK.getStatusCode(), statusCode);
}


But this will send a real request to the API. I am new to Mockito. Can anyone help me how to mock this request?



Edit:



@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));
}


I try to mock the methods but it doesn't work. Still call the real method.










share|improve this question
























  • You could use WireMock to test the communication between clients and servers.
    – Konstantin Yovkov
    Nov 13 at 15:21

















up vote
0
down vote

favorite












I have a class to post POJO to an external API. I want to test this method.



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;
}


I wrote a unit test like this



@Test
public void sendRequest_postAuditEvent_returnOK() {
int statusCode = EventProcessor.sendRequest(event);
assertEquals(Status.OK.getStatusCode(), statusCode);
}


But this will send a real request to the API. I am new to Mockito. Can anyone help me how to mock this request?



Edit:



@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));
}


I try to mock the methods but it doesn't work. Still call the real method.










share|improve this question
























  • You could use WireMock to test the communication between clients and servers.
    – Konstantin Yovkov
    Nov 13 at 15:21















up vote
0
down vote

favorite









up vote
0
down vote

favorite











I have a class to post POJO to an external API. I want to test this method.



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;
}


I wrote a unit test like this



@Test
public void sendRequest_postAuditEvent_returnOK() {
int statusCode = EventProcessor.sendRequest(event);
assertEquals(Status.OK.getStatusCode(), statusCode);
}


But this will send a real request to the API. I am new to Mockito. Can anyone help me how to mock this request?



Edit:



@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));
}


I try to mock the methods but it doesn't work. Still call the real method.










share|improve this question















I have a class to post POJO to an external API. I want to test this method.



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;
}


I wrote a unit test like this



@Test
public void sendRequest_postAuditEvent_returnOK() {
int statusCode = EventProcessor.sendRequest(event);
assertEquals(Status.OK.getStatusCode(), statusCode);
}


But this will send a real request to the API. I am new to Mockito. Can anyone help me how to mock this request?



Edit:



@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));
}


I try to mock the methods but it doesn't work. Still call the real method.







java unit-testing junit mockito jersey-client






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 13 at 17:13

























asked Nov 13 at 15:13









HenlenLee

737




737












  • You could use WireMock to test the communication between clients and servers.
    – Konstantin Yovkov
    Nov 13 at 15:21




















  • You could use WireMock to test the communication between clients and servers.
    – Konstantin Yovkov
    Nov 13 at 15:21


















You could use WireMock to test the communication between clients and servers.
– Konstantin Yovkov
Nov 13 at 15:21






You could use WireMock to test the communication between clients and servers.
– Konstantin Yovkov
Nov 13 at 15:21














2 Answers
2






active

oldest

votes

















up vote
0
down vote













Ideally, the class should take a Client in its constructor so you could replace the real client instance with a mock when testing it.



class EventProcessor {
private Client client;

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

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





share|improve this answer






























    up vote
    0
    down vote













    You can use powerMockito like this post Mocking static methods with Mockito



    If you can mock this returned object ClientBuilder.newClient() you can mock all the other objects in the call chain.



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





    share|improve this answer





















      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53284027%2fhow-to-use-mockito-to-mock-a-request-in-jersey-client%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      0
      down vote













      Ideally, the class should take a Client in its constructor so you could replace the real client instance with a mock when testing it.



      class EventProcessor {
      private Client client;

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

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





      share|improve this answer



























        up vote
        0
        down vote













        Ideally, the class should take a Client in its constructor so you could replace the real client instance with a mock when testing it.



        class EventProcessor {
        private Client client;

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

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





        share|improve this answer

























          up vote
          0
          down vote










          up vote
          0
          down vote









          Ideally, the class should take a Client in its constructor so you could replace the real client instance with a mock when testing it.



          class EventProcessor {
          private Client client;

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

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





          share|improve this answer














          Ideally, the class should take a Client in its constructor so you could replace the real client instance with a mock when testing it.



          class EventProcessor {
          private Client client;

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

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






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 13 at 15:30

























          answered Nov 13 at 15:20









          migron

          665




          665
























              up vote
              0
              down vote













              You can use powerMockito like this post Mocking static methods with Mockito



              If you can mock this returned object ClientBuilder.newClient() you can mock all the other objects in the call chain.



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





              share|improve this answer

























                up vote
                0
                down vote













                You can use powerMockito like this post Mocking static methods with Mockito



                If you can mock this returned object ClientBuilder.newClient() you can mock all the other objects in the call chain.



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





                share|improve this answer























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  You can use powerMockito like this post Mocking static methods with Mockito



                  If you can mock this returned object ClientBuilder.newClient() you can mock all the other objects in the call chain.



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





                  share|improve this answer












                  You can use powerMockito like this post Mocking static methods with Mockito



                  If you can mock this returned object ClientBuilder.newClient() you can mock all the other objects in the call chain.



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






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 13 at 16:03









                  Iván Minguet García

                  11




                  11






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53284027%2fhow-to-use-mockito-to-mock-a-request-in-jersey-client%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      How to send String Array data to Server using php in android

                      Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

                      Is anime1.com a legal site for watching anime?