I cant init my webclient in a test with mockito

  Kiến thức lập trình

I’m working on a project with java spring boot 2.x and java 1.8. In my pom i got the dependencies of junit 4.13.2 and mockito 3.12.4. When i try to run my test i got the problem that my setup function is not running even with the @before annotation so webclient builder is 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<ResponseEntity<String>> responseMono = this.webClient.get()
                    .uri(url)
                    .retrieve()
                    .toEntity(String.class);

            ResponseEntity<String> 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<ResponseEntity<String>> responseMono = this.webClient.get()
                    .uri(url)
                    .retrieve()
                    .toEntity(String.class);

            try{
                ResponseEntity<String> 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();
        }
    }
}

and this test with mockito and 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());
    }
}

but when i try to run the test i got this error

org.mockito.exceptions.misusing.InjectMocksException:
Cannot instantiate @InjectMocks field named ‘starshipService’ of type ‘class com.example.conexatest.conexatest.service.StarshipService’.
You haven’t provided the instance at field declaration so I tried to construct the instance.
However the constructor or the initialization block threw an exception : Cannot invoke “org.springframework.web.reactive.function.client.WebClient$Builder.build()” because the return value of “org.springframework.web.reactive.function.client.WebClient$Builder.baseUrl(String)” is null

when i put a breakpoint in the setup function i cant reach it when i’m debugging

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT