如何模拟Response response = ClientBuilder.newClient()。target(some url).request()。post(Entity.entity(someEntity,MediaType.APPLICATION_JSON))?

时间:2018-11-14 15:21:09

标签: unit-testing junit mockito jersey-2.0

我使用Jersey客户端发布请求,并使用Mockito进行单元测试。问题是我不想在测试中发送真实的请求。我尝试像这样模拟整个过程

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());

但是如何模拟ClientBuilder?

1 个答案:

答案 0 :(得分:0)

您可以使用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 {
        } 
    }