mockito 在Junit中模拟嵌套对象

wrrgggsh  于 2022-11-23  发布在  其他
关注(0)|答案(1)|浏览(271)

我有一个服务我嘲笑这样:

@ExtendWith(MockitoExtension.class)
class MyServiceTest {

@InjectMocks
MyService myService;


    @Test
    void testSendRec() {
       myService.sendDocRec(.. pass params..);
    }

}
该服务:

@Service
public class MyService {

    String sendDocRec( params ) {

       // builds request
       HttpUriRequestBase request = getRequest(  params );

        String response = doRequest(request);
    }

    public String doRequest(ClassicHttpRequest request) {
    String result = null;

        try (CloseableHttpClient httpclient = HttpClients.custom()
                .setConnectionManager(this.connectionManager)
                .setConnectionManagerShared(true) 
                .setDefaultRequestConfig(this.requestConfig)
                .build()) {

            final HttpClientContext clientContext = HttpClientContext.create();

            try (CloseableHttpResponse response = httpclient.execute(request, clientContext)) {

                result = EntityUtils.toString(response.getEntity());
            
            }
        } catch (URISyntaxException e) {
            log.error("Invalid URI {}", e);
        } catch (IOException e) {
            log.error("Failed to make HTTP Request {}", e);
        } catch (ParseException e) {
            log.error("Failed parsing response body {}", e);
        }

        return result;
    }

}

我需要能够模拟“ClosebleHttpResponse response = httpclient.execute(request,clientContext)",这样“response”对象是我提前创建的。我希望一些模拟的when/then结构能起作用?我会很感激关于如何做到这一点的想法。谢谢!

8ehkhllq

8ehkhllq1#

你不能用当前的代码结构来做。httpclient对象是在测试的方法中创建的。所以它不能被模仿。
您需要将httpclient对象的创建委托给另一个方法,该方法属于不同的类(类似于HttpClientFactory类)。该HttpClientFactory类应仅负责创建httpClient示例。如果需要,您可以为该类编写单独的单元测试用例。

@Inject
 private HttpClientFactory httpClientFactory;

      public String doRequest(ClassicHttpRequest request) {
        String result = null;
    
            try (CloseableHttpClient httpclient = httpClientFactory.getInstance()) {
    
                final HttpClientContext clientContext = HttpClientContext.create();
    
                try (CloseableHttpResponse response = httpclient.execute(request, clientContext)) {
    
                    result = EntityUtils.toString(response.getEntity());
                
                }
            } catch (URISyntaxException e) {
                log.error("Invalid URI {}", e);
            } catch (IOException e) {
                log.error("Failed to make HTTP Request {}", e);
            } catch (ParseException e) {
                log.error("Failed parsing response body {}", e);
            }
    
            return result;
        }

现在你可以像下面这样嘲弄回应:

@Mock
 private HttpClientFactory httpClientFactory;

public String testDoRequest(ClassicHttpRequest request) {
....
    CloseableHttpClient mockedClient = mock(CloseableHttpClient.class);
    CloseableHttpResponse mockedResponse = mock(CloseableHttpResponse.class);
    when(httpClientFactory.getInstance()).thenReturn(mockedClient);
    when(mockedClient.execute(eq(request), any(clientContext))).thenReturn(mockedResponse);
....}

相关问题