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:
-
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. -
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):
- -> at com.impl.SelfServiceCoreClaimImplTest.testGenerateJsonFile_Success(SelfServiceCoreClaimImplTest.java:147)
- -> 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.
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.POS
T, 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.
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.