RestTemplate Mocking not working in Junit

I have this method and tried everything but mocking is not working as expected

@Override
    public ClaimSubmissionResponse generateJsonFileProfessional(String claimType, String correlationId,
            String jsonContent, String authToken) {
        ClaimSubmissionResponse claimSubmissionResponse = new ClaimSubmissionResponse();
        try {
            if (isSelfServicePortalServerAvailable(selfServicePortalURL)) {
                HttpHeaders headers = populateTokenHeaders(authToken);
                String corelationId = UUID.randomUUID().toString();
                InetAddress ipAddress = InetAddress.getLocalHost();
                HttpEntity<String> request = new HttpEntity<>(jsonContent, headers);
                String claimSubmissionAPI = selfServicePortalURL + Endpoints.SUBMIT_CLAIM_PROFESSIONAL;
                processRequestAudit(jsonContent, corelationId, corelationId, ipAddress.toString(), "Generate Json File",
                        "Claim Submission");
                UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(claimSubmissionAPI)
                        .queryParam("claimType", claimType).queryParam("correlationId", correlationId);
                ResponseEntity<ClaimSubmissionResponse> response = restTemplate.exchange(
                        builder.buildAndExpand().toUri(), HttpMethod.POST, request, ClaimSubmissionResponse.class);
                claimSubmissionResponse = response.getBody();
                processResponseAudit(claimSubmissionResponse, "", corelationId, corelationId);
            } else {
                log.info(SELF_SERVICE_PORTAL_UNAVAILABLE_MESSAGE);
            }
        } catch (Exception cause) {
            log.error("The Error While Executing the API Call :: {} ", cause.getMessage());
        }
        return claimSubmissionResponse;
    }

junit test case

 @Test
public void testGenerateJsonFileProfessional_Success() throws Exception {
    // Mocking external methods and variables
    String claimType = "type1";
    String correlationId = UUID.randomUUID().toString();
    String jsonContent = "{}";
    String authToken = "token123";
    String corelationId = UUID.randomUUID().toString();
    InetAddress ipAddress = InetAddress.getLocalHost();
    // Mocking isSelfServicePortalServerAvailable
    when(selfServiceCoreClaimImpl.isSelfServicePortalServerAvailable(selfServicePortalURL)).thenReturn(true);
    // Mocking populateTokenHeaders
    when(selfServiceCoreClaimImpl.populateTokenHeaders(authToken)).thenReturn(httpHeaders);
    // Mocking RestTemplate response
    ClaimSubmissionResponse expectedResponse = new ClaimSubmissionResponse();
    ResponseEntity<ClaimSubmissionResponse> mockResponse = new ResponseEntity<>(expectedResponse, HttpStatus.OK);
    // UriComponentsBuilder mock setup
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(selfServicePortalURL)
            .queryParam("claimType", claimType)
            .queryParam("correlationId", correlationId);
    when(restTemplateTest.exchange(
            builder.buildAndExpand().toUri(), HttpMethod.POST, new HttpEntity<>(jsonContent, httpHeaders), ClaimSubmissionResponse.class))
        .thenReturn(mockResponse);
    // Call the method under test
    ClaimSubmissionResponse actualResponse = selfServiceCoreClaimImpl.generateJsonFileProfessional(claimType, correlationId, jsonContent, authToken);
    // Assertions
    assertNotNull(actualResponse);
    assertEquals(expectedResponse, actualResponse);
    // Verify RestTemplate was called
    verify(restTemplateTest).exchange(
            builder.buildAndExpand().toUri(), HttpMethod.POST, new HttpEntity<>(jsonContent, httpHeaders), ClaimSubmissionResponse.class);
}

}

getting this eeror

org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be ‘a method call on a mock’.
For example:
when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:

  1. you stub either of: final/private/equals()/hashCode() methods.
    Those methods cannot be stubbed/verified.
    Mocking methods declared on non-public parent classes is not supported.

  2. inside when() you don’t call method on mock but on some other object.

    at com.acentra.ssp.impl.SelfServiceCoreClaimImplTest.testGenerateJsonFileProfessional_Success(SelfServiceCoreClaimImplTest.java:170)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)

Not sure where i am doing wrong. Thanks if someone can help. I stuck in this from past 2 days. tried everthing but not worked.

updated the test method to this :

 @Test
public void testGenerateJsonFile_Success() {
    ClaimSubmissionResponse mockResponse = new ClaimSubmissionResponse();
    ResponseEntity<ClaimSubmissionResponse> responseEntity = mock(ResponseEntity.class);
    when(responseEntity.getBody()).thenReturn(mockResponse);
    when(restTemplate.exchange(any(), eq(HttpMethod.POST), any(HttpEntity.class), eq(ClaimSubmissionResponse.class))).thenReturn(responseEntity);

    ClaimSubmissionResponse response = selfServiceCoreClaimImpl.generateJsonFileProfessional("claimType", "correlationId", "jsonContent", "testdata");
    assertNotNull(response);
}

then
response is getting null here

ResponseEntity<ClaimSubmissionResponse> response = restTemplate.exchange(
                        builder.buildAndExpand().toUri(), HttpMethod.POST, request, ClaimSubmissionResponse.class);
                claimSubmissionResponse = response.getBody();

error is

org.mockito.exceptions.misusing.UnnecessaryStubbingException:
Unnecessary stubbings detected.
Clean & maintainable test code requires zero unnecessary code.
Following stubbings are unnecessary (click to navigate to relevant line of code):

  1. -> at com.impl.SelfServiceCoreClaimImplTest.testGenerateJsonFile_Success(SelfServiceCoreClaimImplTest.java:147)
  2. -> at com.impl.SelfServiceCoreClaimImplTest.testGenerateJsonFile_Success(SelfServiceCoreClaimImplTest.java:148)
    Please remove unnecessary stubbings or use ‘lenient’ strictness. More info: javadoc for UnnecessaryStubbingException class.
    at org.mockito.junit.jupiter.MockitoExtension.afterEach(MockitoExtension.java:192)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)

The MissingMethodInvocationException usually pops up when you try to use the when() function on something that’s not actually a mock. This can happen if restTemplateTest hasn’t been set up correctly as a mock or if there’s a problem with how you’re using mock() or @Mock annotations.

Double-check restTemplateTest: Make sure you’ve annotated restTemplateTest with @Mock. Also, don’t forget to initialize your mocks—either in a @Before method or by using MockitoAnnotations.initMocks(). If you’re working with a testing framework like Spring Boot, using @ExtendWith(MockitoExtension.class) should handle this part for you.

New contributor

Natarajan D is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

3

Use any(URI.class) for the URI in the exchange mock, as UriComponentsBuilder dynamically creates the URI, and mocking a specific URI might not match and ensure that the HttpMethod.POST, HttpEntity, and response class (ClaimSubmissionResponse.class) are correctly stubbed with eq() and any().

2

Add @InjectMocks annotation where you have defined instance for selfServiceCoreClaimImpl in test class. That should help in injecting the mocks that you have defined in the test case.

New contributor

The_IT_Girl is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật