Mocking Apache HTTPClient using Mockito

后端 未结 5 787
走了就别回头了
走了就别回头了 2020-12-25 11:24

I\'m trying to mock Apache HttpClient Interface in order to mock one of its methods mentioned below to return a stubbed JSON object in response.

HttpResponse         


        
5条回答
  •  一生所求
    2020-12-25 12:04

    You can do this easily using PowerMockito which can also mock final/static methods, private methods and anonymous classes easily. Here's the sample code for mocking http request. JSON_STRING_DATA is any string which you want to get from execute method.

    PowerMockito.mockStatic(DefaultHttpClient.class);
        HttpClient defaultHttpClientMocked =  PowerMockito.mock(DefaultHttpClient.class);        
        PowerMockito.when(defaultHttpClientMocked.execute(Mockito.any(HttpPost.class))).thenReturn(createMockedHTTPResponse(JSON_STRING_DATA));
    

提交回复
热议问题