HenlenLee
HenlenLee

Reputation: 445

How to mock Response response = ClientBuilder.newClient().target(some url).request().post(Entity.entity(someEntity, MediaType.APPLICATION_JSON))?

I use Jersey client to post request and use Mockito to do unit test. The problem is I don't want to send a real request in the test. I try to mock the whole process like this

when(m_client.target(anyString())).thenReturn(m_webTarget);
when(m_webTarget.request()).thenReturn(m_builder);
when(m_builder.post(Entity.entity(m_Event, MediaType.APPLICATION_JSON))).thenReturn(m_response); 
when(m_response.getStatus())
.thenReturn(Response.Status.BAD_REQUEST.getStatusCode());

But how to mock the ClientBuilder?

Upvotes: 1

Views: 3067

Answers (1)

want2learn
want2learn

Reputation: 2511

You can achieve this by using powermock.

 @RunWith(PowerMockRunner.class)
    @PrepareForTest(ClientBuilder.class)
    public class YourTestClass{

        //create a mock client here
        Client mockClient = Mockito.mock(Client.class);

        // use powermockito to mock new call

        @Before
        public void setUp() throws Exception {
            PowerMockito.mockStatic(ClientBuilder.class);
            PowerMockito.when(ClientBuilder.newClient()).thenReturn(this.mockClient); 
        //Now you can use mockClient to mock any call using when... then..

        }

        @Test
        public void yourTest() throws Exception {
        } 
    }

Upvotes: 2

Related Questions