In this test case mockStatic.when(() -> selfServiceDaoHelper.auditApiRequestData(any(MapSqlParameterSource.class))).thenReturn(1);
when(restTemplate.exchange(any(), eq(HttpMethod.POST), any(HttpEntity.class), eq(MemberDataValidationResponse.class))) .thenReturn(ResponseEntity.ok(mockResponse));
these calls are not working and hitting the method. Can anyone please help me on this.
@Test
public void testValidateMemberData_Success() throws Exception {
MemberValidationRequest memberRequest = new MemberValidationRequest();
memberRequest.setCorelationIdentifier("123");
MemberDataValidationResponse mockResponse = new MemberDataValidationResponse();
mockResponse.setStatus("200");
HttpHeaders headers = SelfServiceValidation.populateTokenHeaders();
HttpEntity<String> httpEntity = new HttpEntity<>(new JSONObject(memberRequest).toString(), headers);
ApplicationContext applicationContext = Mockito.mock(ApplicationContext.class);
SelfServiceDaoImpl selfServiceDao = Mockito.mock(SelfServiceDaoImpl.class);
SelfServiceDaoHelper selfServiceDaoHelperTest = new SelfServiceDaoHelper();
selfServiceDaoHelperTest.setApplicationContext(applicationContext);
when(applicationContext.getBean(SelfServiceDaoImpl.class)).thenReturn(selfServiceDao);
Mockito.when(postgresJdbcTemplateTest.update(any(), any(MapSqlParameterSource.class))).thenReturn(1);
when(restTemplate.exchange(any(), eq(HttpMethod.POST), any(HttpEntity.class), eq(MemberDataValidationResponse.class)))
.thenReturn(ResponseEntity.ok(mockResponse));
try (MockedStatic<SelfServiceDaoHelper> mockStatic = mockStatic(SelfServiceDaoHelper.class)) {
// this down mock is not working as expected
mockStatic.when(() -> selfServiceDaoHelper.auditApiRequestData(any(MapSqlParameterSource.class))).thenReturn(1);
mockStatic.when(()->applicationContext.getBean(SelfServiceDaoImpl.class)).thenReturn(selfServiceDao);
assertEquals(1, SelfServiceDaoHelper.auditApiRequestData(new MapSqlParameterSource()));
};
MemberDataValidationResponse result = SelfServiceValidation.validateMemberData(memberRequest);
assertNotNull(result);
assertEquals("200", result.getStatus());
}
the methods calling are as below :
public static MemberDataValidationResponse validateMemberData(MemberValidationRequest memberValidationRequest)
throws Exception {
MemberDataValidationResponse memberValidateResponse = new MemberDataValidationResponse();
try {
if (isSelfServicePortalServerAvailable(selfServicePortalURL)) {
String corelationId = UUID.randomUUID().toString();
InetAddress ipAddress = InetAddress.getLocalHost();
String spanId = corelationId + SelfServicePortalConstants.MEMBER_VALIDATION_CODE;
HttpHeaders headers = populateTokenHeaders();
RestTemplate restTemplate = new RestTemplate();
String validateMemberAPI = selfServicePortalURL + Endpoints.MEMBER_VALIDATION;
log.info("Self Service Portal API URL :{}", validateMemberAPI);
JSONObject jsonObj = new JSONObject(memberValidationRequest);
String requestBody = jsonObj.toString();
HttpEntity<String> request = new HttpEntity<>(requestBody, headers);
processRequestAudit(memberValidationRequest, corelationId, spanId, ipAddress.toString(),
"Member Validation", "Claim Submission");
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(validateMemberAPI);
ResponseEntity<MemberDataValidationResponse> response = restTemplate.exchange(
builder.buildAndExpand().toUri(), HttpMethod.POST, request, MemberDataValidationResponse.class);
memberValidateResponse = (MemberDataValidationResponse) response.getBody();
processResponseAudit(memberValidateResponse, "", spanId, corelationId);
} else {
log.info(SELF_SERVICE_PORTAL_UNAVAILABLE_MESSAGE);
}
} catch (Exception cause) {
throw new RuntimeException(cause);
}
return memberValidateResponse;
}
The is the second method call
public static String processRequestAudit(Object inquireClaimFilterRequest, String corelationId, String spanId,
String ipAddress, String serviceType, String responseStatus)
throws UnknownHostException, JsonProcessingException {
String auditStatus = "";
ObjectMapper objectMapper = new ObjectMapper();
String requestJson = objectMapper.writeValueAsString(inquireClaimFilterRequest);
LocalDateTime myDateObj = LocalDateTime.now();
DateTimeFormatter dateStampObj = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
String dateStamp = myDateObj.format(dateStampObj);
LocalDateTime localDateTime = LocalDateTime.parse(dateStamp, dateStampObj);
MapSqlParameterSource auditParams = new MapSqlParameterSource();
auditParams.addValue(SRVC_TYPE_NAME, serviceType);
auditParams.addValue(CORLTN_ID, corelationId);
auditParams.addValue(RQST_IP_ADRS, ipAddress);
auditParams.addValue(RQST_TIMESTAMP, Timestamp.valueOf(myDateObj));
auditParams.addValue(RQST_BODY, requestJson, java.sql.Types.OTHER);
auditParams.addValue(RSPNS_TIMESTAMP, null);
auditParams.addValue(RSPNS_BODY, null, java.sql.Types.OTHER);
auditParams.addValue(SRVC_RSPNS_STATUS, responseStatus);
auditParams.addValue(OPRTNL_FLAG, OPRTNL_FLAG_A_VAL);
auditParams.addValue(CREATED_BY, "1");
auditParams.addValue(CREATED_DATE, localDateTime, java.sql.Types.TIMESTAMP);
auditParams.addValue(MODIFIED_BY, "1");
auditParams.addValue(MODIFIED_DATE, localDateTime, java.sql.Types.TIMESTAMP);
auditParams.addValue(SPAN_ID, spanId);
int auditResponse = SelfServiceDaoHelper.auditApiRequestData(auditParams);
if (auditResponse == 1) {
auditStatus = "Audit Data Inserted Successfully";
} else if (auditResponse == 0) {
auditStatus = "Audit Data Insertion Failed";
}
return auditStatus;
}
You are using try-with-resource block for your MockStatic:
try (MockedStatic<SelfServiceDaoHelper> mockStatic = mockStatic(SelfServiceDaoHelper.class)) {
// this down mock is not working as expected
mockStatic.when(() -> selfServiceDaoHelper.auditApiRequestData(any(MapSqlParameterSource.class))).thenReturn(1);
mockStatic.when(()->applicationContext.getBean(SelfServiceDaoImpl.class)).thenReturn(selfServiceDao);
assertEquals(1, SelfServiceDaoHelper.auditApiRequestData(new MapSqlParameterSource()));
};
Static stubs are active only in scope of this block. They are not active after you exit it.
You need to call your method under test in scope of this block.
For restTemplate You are creating a new RestTemplate in method under test RestTemplate restTemplate = new RestTemplate(); thus stubbing in test does not have any effect. You need to pass RestTemplate to class under test - ideally in constructor.