Anonymous
RestTemplate Mocking не работает в Junit
Сообщение
Anonymous » 25 сен 2024, 05:56
У меня есть этот метод, я попробовал все, но издевательство не работает должным образом
Код: Выделить всё
@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;
}
Тестовый пример Junit
Код: Выделить всё
@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)
Не знаю, где я делаю неправильно. Спасибо, если кто-то может помочь. Я застрял в этом последние 2 дня. все пробовал, но не помогло.
Подробнее здесь:
https://stackoverflow.com/questions/790 ... g-in-junit
1727232975
Anonymous
У меня есть этот метод, я попробовал все, но издевательство не работает должным образом [code]@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; } [/code] Тестовый пример Junit [code] @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); } [/code] получение этой ошибки org.mockito.Exceptions. misusing.MissingMethodInvocationException: when() требует аргумента, который должен быть «вызовом метода в макете». Например: when(mock.getArticles()).thenReturn(articles ); Кроме того, эта ошибка может появиться по следующим причинам: [list] [*] вы заглушаете любой из методов: 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) [/list] [b]Не знаю, где я делаю неправильно. Спасибо, если кто-то может помочь. Я застрял в этом последние 2 дня. все пробовал, но не помогло.[/b] Подробнее здесь: [url]https://stackoverflow.com/questions/79020990/resttemplate-mocking-not-working-in-junit[/url]