Код: Выделить всё
@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 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 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;
}
Код: Выделить всё
@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 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);
}
org.mockito.Exceptions. misusing.MissingMethodInvocationException:
when() требует аргумента, который должен быть «вызовом метода в макете».
Например:
when(mock.getArticles()).thenReturn(articles );
Кроме того, эта ошибка может появиться по следующим причинам:
-
вы заглушаете любой из методов: Final/private/equals()/hashCode().
Эти методы не могут быть заглушены/проверены.
Издевательские методы, объявленные в непубличном родителе классы не поддерживаются. - внутри if() вы вызываете метод не для макета, а для какого-то другого объекта.at com.acentra.ssp.impl.SelfServiceCoreClaimImplTest.testGenerateJsonFileProfessional_Success(SelfServiceCoreClaimImplTest.java:170)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
в java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
в java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
обновил метод тестирования до этого:
Код: Выделить всё
@Test
public void testGenerateJsonFile_Success() {
ClaimSubmissionResponse mockResponse = new ClaimSubmissionResponse();
ResponseEntity 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);
}
ответ здесь становится нулевым
Код: Выделить всё
ResponseEntity response = restTemplate.exchange(
builder.buildAndExpand().toUri(), HttpMethod.POST, request, ClaimSubmissionResponse.class);
claimSubmissionResponse = response.getBody();
org.mockito.Exceptions.misusing.UnnecessaryStuddingException:
Обнаружены ненужные заглушки.Чистый и удобный в сопровождении тестовый код не требует лишнего кода.
Следующие заглушки не нужны (нажмите, чтобы перейти к соответствующей строке кода):
- -> на com.impl.SelfServiceCoreClaimImplTest.testGenerateJsonFile_Success(SelfServiceCoreClaimImplTest.java:147)
- -> на com.impl.SelfServiceCoreClaimImplTest.testGenerateJsonFile_Success(SelfServiceCoreClaimImplTest.java :148)
Пожалуйста, удалите ненужные заглушки или используйте «мягкую» строгость. Дополнительная информация: javadoc для класса UnnecessaryStublingException.
на org.mockito.junit.jupiter.MockitoExtension.afterEach(MockitoExtension.java:192)
на java.base/java.util.ArrayList.forEach(ArrayList. java:1511)
на java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
Подробнее здесь: https://stackoverflow.com/questions/790 ... g-in-junit
Мобильная версия