Mocked HttpClient calls actual method

后端 未结 1 334
北恋
北恋 2021-01-28 11:53

In my test class I am mocking HTTPclient but when I run test class it calls actual method instead of mock at line

 final HttpResponse response = httpClient.execu         


        
相关标签:
1条回答
  • 2021-01-28 12:34

    From the code snippet shared it is evident that HttpClient and HttpPost are instantiated via new operator instead of using any instance level injected (i.e. autowired) objects.

     final HttpClient httpClient = new DefaultHttpClient();
     final HttpPost postRequest = new HttpPost(someURL);
    

    Thus the @InjectMocks and @Mock essentially have no effect and the real instance of HttpClient and HttpPost are used when invoked from test class; which explains the error encountered.

    In this particular scenario Mockito (perhaps any mocking framework) can't help. To proceed, if possible, refactor the code under test such as to use the instance level injected object(s) instead of using the instance created via new operator.

    0 讨论(0)
提交回复
热议问题