Программисты JAVA общаются здесь
Anonymous
Mockito Не возвращает ложный ответ
Сообщение
Anonymous » 11 ноя 2024, 20:08
Тестируемый метод:
Код: Выделить всё
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Component
public class Adapter {
private static final Logger LOGGER = LoggerFactory
.getLogger(Adapter.class);
private final RestTemplate restTemplate;
public Adapter(RestTemplate restTemplate){
this.restTemplate = restTemplate;
}
public void getPost(String titleId,List normalize) {
try{
PostingTitle postingTitle = null;
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "application/json");
headers.set("Accept", "*/*");
HttpEntity request = new HttpEntity(CommonUtils.createPostingBody(titleId).toString(), headers);
ResponseEntity response = restTemplate.postForEntity(postPostURL, request, String.class);
}
Модульный тест:
Код: Выделить всё
import org.mockito.*;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.core.env.Environment;
import org.springframework.http.*;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
public class AdapterTest {
@Mock
private RestTemplate restTemplate;
@InjectMocks
private Adapter lcAdap;
@Mock
private ResponseEntity response;
@Captor
private ArgumentCaptor entityCaptor;
@Test
public void testGetExtract_Success() throws Exception {
// Setup
String description = "Some description";
List normalizedDetailsList = new ArrayList();
String jsonResponse = "{ \"data\": "test" }";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
Map map = new HashMap();
map.put("text", finalDescription);
HttpEntity entity = new HttpEntity(map, headers);
ResponseEntity mockResponse = new ResponseEntity(jsonResponse, HttpStatus.OK);
// Mock the behavior of RestTemplate's postForEntity
Mockito.when(restTemplate.postForEntity(ArgumentMatchers.anyString(),ArgumentMatchers.any(),ArgumentMatchers.any()))
.thenReturn(mockResponse);
// Action
lc.getPost(description, normalizedDetailsList);
}
}
Приведенный выше модульный тест не возвращает ответ. Он возвращает ноль для ложного ответа. Может ли кто-нибудь помочь с этим правильным фиктивным ответом... для этого метода?
Я хотел бы извлечь фиктивный ответ, который в дальнейшем может работать так, как ожидалось, для анализа данных и утверждения данных.< /п>
Подробнее здесь:
https://stackoverflow.com/questions/791 ... k-response
1731344888
Anonymous
[b]Тестируемый метод:[/b] [code] import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; @Component public class Adapter { private static final Logger LOGGER = LoggerFactory .getLogger(Adapter.class); private final RestTemplate restTemplate; public Adapter(RestTemplate restTemplate){ this.restTemplate = restTemplate; } public void getPost(String titleId,List normalize) { try{ PostingTitle postingTitle = null; HttpHeaders headers = new HttpHeaders(); headers.set("Content-Type", "application/json"); headers.set("Accept", "*/*"); HttpEntity request = new HttpEntity(CommonUtils.createPostingBody(titleId).toString(), headers); ResponseEntity response = restTemplate.postForEntity(postPostURL, request, String.class); } [/code] [b]Модульный тест:[/b] [code] import org.mockito.*; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.core.env.Environment; import org.springframework.http.*; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.web.client.RestTemplate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) public class AdapterTest { @Mock private RestTemplate restTemplate; @InjectMocks private Adapter lcAdap; @Mock private ResponseEntity response; @Captor private ArgumentCaptor entityCaptor; @Test public void testGetExtract_Success() throws Exception { // Setup String description = "Some description"; List normalizedDetailsList = new ArrayList(); String jsonResponse = "{ \"data\": "test" }"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); Map map = new HashMap(); map.put("text", finalDescription); HttpEntity entity = new HttpEntity(map, headers); ResponseEntity mockResponse = new ResponseEntity(jsonResponse, HttpStatus.OK); // Mock the behavior of RestTemplate's postForEntity Mockito.when(restTemplate.postForEntity(ArgumentMatchers.anyString(),ArgumentMatchers.any(),ArgumentMatchers.any())) .thenReturn(mockResponse); // Action lc.getPost(description, normalizedDetailsList); } } [/code] Приведенный выше модульный тест не возвращает ответ. Он возвращает ноль для ложного ответа. Может ли кто-нибудь помочь с этим правильным фиктивным ответом... для этого метода? Я хотел бы извлечь фиктивный ответ, который в дальнейшем может работать так, как ожидалось, для анализа данных и утверждения данных.< /п> Подробнее здесь: [url]https://stackoverflow.com/questions/79178492/mockito-not-returning-the-mock-response[/url]