Я не могу запустить свой веб-клиент в тесте с помощью MockitoJAVA

Программисты JAVA общаются здесь
Anonymous
Я не могу запустить свой веб-клиент в тесте с помощью Mockito

Сообщение Anonymous »

Я работаю над проектом с использованием Java Spring Boot 2.x и Java 1.8. В моем pom я получил зависимости Junit 4.13.2 и Mockito 3.12.4. Когда я пытаюсь запустить тест, у меня возникла проблема: моя функция настройки не работает даже с аннотацией @before, поэтому построитель веб-клиента имеет значение null

Код: Выделить всё

@Service
public class StarshipService {

private final WebClient webClient;

@Autowired
public StarshipService(WebClient.Builder webClientBuilder) {
this.webClient = webClientBuilder.baseUrl("https://www.swapi.tech/api").build();
}

public StarshipResponse getStarships(int page, int size, String nameOrId){
try {

// Si nameOrId es un número, busca por ID
if (nameOrId != null && nameOrId.matches("\\d+")) {
return getStarshipById(nameOrId);
}

UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://www.swapi.tech/api/starships");

if (page != 0){
builder.queryParam("page", page);
}
builder.queryParam("limit", size);
if (nameOrId != null && !nameOrId.isEmpty()) {
builder.queryParam("name", nameOrId);
}

String url = builder.toUriString();

Mono responseMono = this.webClient.get()
.uri(url)
.retrieve()
.toEntity(String.class);

ResponseEntity responseEntity = responseMono.block();

if (responseEntity != null && responseEntity.getStatusCode().is2xxSuccessful()) {
String responseBody = responseEntity.getBody();
if (responseBody != null && responseBody.contains("results")) {
return StarWarsParseService.parseStandardStarshipResponse(responseBody);
} else if (responseBody != null && responseBody.contains("result")) {
return StarWarsParseService.parseSearchStarshipResponse(responseBody);
}
}
return new StarshipResponse();
} catch (HttpClientErrorException e){
System.err.println("Error al llamar a la API de Star Wars: " + e.getMessage());
e.printStackTrace();
return new StarshipResponse();
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}

public StarshipResponse getStarshipById(String id) throws JsonProcessingException {
try {
String url = "https://www.swapi.tech/api/starships/" + id;

Mono responseMono = this.webClient.get()
.uri(url)
.retrieve()
.toEntity(String.class);

try{
ResponseEntity responseEntity = responseMono.block();
if (responseEntity != null && responseEntity.getStatusCode().is2xxSuccessful()) {
return StarWarsParseService.parseIdStarshipResponse(responseEntity.getBody());
} else {
System.err.println("Unexpected response or status code: " + responseEntity);
return new StarshipResponse();
}
}catch (WebClientResponseException.NotFound ex){
System.err.println("Person with ID " + id + " not found in SWAPI");
StarshipResponse starshipResponse = new StarshipResponse();
starshipResponse.setResults(new ArrayList());
starshipResponse.setTotal_records(0);
starshipResponse.setTotal_pages(1);
return starshipResponse;
}
} catch (HttpClientErrorException e) {
System.err.println("Error al llamar a la API de Star Wars: " + e.getMessage());
e.printStackTrace();
return new StarshipResponse();
}
catch (Exception e) {
System.err.println("Unexpected error: "  + e.getMessage());
e.printStackTrace();
return new StarshipResponse();
}
}
}
и этот тест с помощью Mockito и Junit

Код: Выделить всё

@RunWith(MockitoJUnitRunner.class)
@SpringBootTest
public class StarshipServiceTest {

@Mock
private WebClient.Builder webClientBuilder;

@Mock
private WebClient webClient;

@Mock
private WebClient.RequestHeadersUriSpec requestHeadersUriSpec;

@Mock
private WebClient.RequestHeadersSpec requestHeadersSpec;

@Mock
private WebClient.ResponseSpec responseSpec;

@InjectMocks
private StarshipService starshipService;

@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
when(webClientBuilder.baseUrl(anyString())).thenReturn(webClientBuilder);
when(webClientBuilder.build()).thenReturn(webClient);
}

@Test
public void testGetStarships() throws JsonProcessingException {
// Mock the WebClient behavior
when(webClient.get()).thenReturn(requestHeadersUriSpec);
when(requestHeadersUriSpec.uri(anyString())).thenReturn(requestHeadersSpec);
when(requestHeadersSpec.retrieve()).thenReturn(responseSpec);
when(responseSpec.toEntity(String.class)).thenReturn(Mono.just(new ResponseEntity("{\"results\": []}", HttpStatus.OK)));

// Call the method to test
StarshipResponse response = starshipService.getStarships(1, 10, null);

// Assert the response
assertNotNull(response);
assertEquals(0, response.getResults().size());
}

@Test
public void testGetStarshipById() throws JsonProcessingException {
// Mock the WebClient behavior
when(webClient.get()).thenReturn(requestHeadersUriSpec);
when(requestHeadersUriSpec.uri(anyString())).thenReturn(requestHeadersSpec);
when(requestHeadersSpec.retrieve()).thenReturn(responseSpec);
when(responseSpec.toEntity(String.class)).thenReturn(Mono.just(new ResponseEntity("{\"result\": {\"properties\": {\"name\": \"Millennium Falcon\"}}}", HttpStatus.OK)));

// Call the method to test
StarshipResponse response = starshipService.getStarshipById("10");

// Assert the response
assertNotNull(response);
assertEquals("Millennium Falcon", response.getResults().get(0).getName());
}

@Test
public void testGetStarshipByIdNotFound() throws JsonProcessingException {
// Mock the WebClient behavior for 404 Not Found
when(webClient.get()).thenReturn(requestHeadersUriSpec);
when(requestHeadersUriSpec.uri(anyString())).thenReturn(requestHeadersSpec);
when(requestHeadersSpec.retrieve()).thenReturn(responseSpec);
when(responseSpec.toEntity(String.class)).thenReturn(Mono.error(new WebClientResponseException(404, "Not Found", null, null, null)));

// Call the method to test
StarshipResponse response = starshipService.getStarshipById("0");

// Assert the response
assertNotNull(response);
assertEquals(0, response.getTotal_records());
}
}
но когда я пытаюсь запустить тест, я получаю эту ошибку
org.mockito.Exceptions.misusing.InjectMocksException:
Невозможно создать экземпляр Поле @InjectMocks с именем «starshipService» типа «класс com.example.conexatest.conexatest.service.StarshipService».
Вы не указали экземпляр при объявлении поля, поэтому я попытался создать экземпляр.
Однако конструктор или блок инициализации выдал исключение: невозможно вызвать «org.springframework.web.reactive.function.client.WebClient$Builder.build()», поскольку возвращаемое значение «org.springframework.web.reactive.function. client.WebClient$Builder.baseUrl(String)" имеет значение null
когда я помещаю точку останова в функцию настройки, я не могу достичь ее во время отладки

Подробнее здесь: https://stackoverflow.com/questions/787 ... th-mockito

Вернуться в «JAVA»