Unit testing: How to get the full coverage of the tested method

Issue

This Content is from Stack Overflow. Question asked by WorkWork

I’m writing unit tests for a Spring Boot Service, and I want to get the full coverage of the GET method. Here’s my GET method:

public void updateCar(String id, String carModel, Integer HP, Integer year, String designer) {
    Garage garage = garageRepository.findById(id)
            .orElseThrow(() -> new IllegalStateException(
                    "A car with the id " + id + " is not in our Garage."));
    if(carModel != null && carModel.length() > 0 && !Objects.equals(garage.getCarModel(), carModel)) {
        garage.setCarModel(carModel);
    }
    if(HP != null && !Objects.equals(garage.getHP(), HP)) {
        garage.setHP(HP);
    }
    if(year != null && !Objects.equals(garage.getYear(), year)) {
        garage.setYear(year);
    }
    if(designer != null && designer.length() > 0 && !Objects.equals(garage.getDesigner(), designer)) {
        garage.setDesigner(designer);
    }
    garageRepository.save(garage);
}
}

And here is the test method I wrote:

 @Test
    @DisplayName("Update Car Test")
    void testUpdateCar() {

    Garage updatedGarage = new Garage();
    String id = "630ca281f12905d5f5249f08";
    String carModel = "Updated carModel";
    int HP = 480;
    int year = 1964;
    String designer = "Updated designer";

    updatedGarage.setId(id);
    updatedGarage.setCarModel(carModel);
    updatedGarage.setHP(HP);
    updatedGarage.setYear(year);
    updatedGarage.setDesigner(designer);

    when(garageRepository.findById(id))
            .thenReturn(Optional.of(updatedGarage));
    garageService.updateCar(id, carModel, HP, year, designer);

    when(garageRepository.save(updatedGarage))
            .thenReturn(updatedGarage);
    verify(garageRepository).findById(id);
    }

With the test, I only get partial coverage. To be precise, the test didn’t include garage.setCarModel(carModel), garage.setHP(HP), garage.setYear(year) nor the garage.setDesigner(designer) from the updateCar method. Can anyone give me a clue or point me in the right direction, on how to get the full coverage?



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?