简体   繁体   English

Mocking a 嵌套在 Junit 中的 Object

[英]Mocking a Nested Object in Junit

I have a service I am mocking like this:我有这样的服务,我是 mocking:

@ExtendWith(MockitoExtension.class)
class MyServiceTest {

@InjectMocks
MyService myService;



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

} }

the service:服务:

@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;
    }

}

I need to be able to mock the "CloseableHttpResponse response = httpclient.execute(request, clientContext)", such that the "response" object is something I create ahead of time.我需要能够模拟“CloseableHttpResponse response = httpclient.execute(request, clientContext)”,这样“response”object 就是我提前创建的。 I am hoping some mocking when/then constructs would work for this?我希望一些 mocking 什么时候/然后构造适用于此? I would grateful for ideas on how to do this.我很感激关于如何做到这一点的想法。 Thanks!谢谢!

You can't do it using the current code structure.您不能使用当前的代码结构来做到这一点。 httpclient object is getting created within the method under test. httpclient object 正在被测方法中创建。 So it can't be mocked.所以它不能被嘲笑。

You need to delegate httpclient object creation to another method with belongs to a different class (something similar to HttpClientFactory class).您需要将 httpclient object 的创建委托给另一个属于不同 class 的方法(类似于 HttpClientFactory 类)。 That HttpClientFactory class should only be responsible for creating httpClient instances. HttpClientFactory class 应该只负责创建 httpClient 实例。 If you need you can write separate unit test case for the class.如果需要,可以为 class 编写单独的单元测试用例。

 @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;
        }

Now you can mock response like below:现在你可以像下面这样模拟响应:

 @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);
....}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM