pussyCat
pussyCat

Reputation: 55

Unit test for SpringBoot Service PUT method

I'm writing Unit tests for my SpringBoot application and I'm completely lost in the PUT method. I'm getting Expecting code to raise a throwable but I guess the complete test is wrong.

Here's my code:

the PUT method in the Service

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);
}

My Repository:

@org.springframework.stereotype.Repository
public interface GarageRepository extends MongoRepository<Garage, String> {

Optional<Garage> findByCarModel(String carModel); }

And here's a test:

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

String id = "630ca281f12905d5f5249f08";
String carModel = "Shelby Cobra";
int HP = 485;
int year = 1964;
String designer = "Carroll Shelby";

Garage testGarage = new Garage();
testGarage.setId(id);

given(garageRepository.findById(testGarage.getId()))
        .willReturn(Optional.of(testGarage));
assertThatThrownBy(() -> garageService.updateCar(id,carModel,HP,year,designer))
        .isInstanceOf(IllegalStateException.class)
        .hasMessageContaining("A car with the id " + id + " is not in our Garage.");
verify(garageRepository.findById(id).get().getId());
}

Other tests are fine (Create, Read, and Delete), but just this one confuses the hell out of me. I don't think the Controller is necessary, so I skipped adding it.

Upvotes: 0

Views: 233

Answers (1)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79807

You're setting up your test so that findById is returning an Optional containing testGarage. That is, something is actually being found.

The updateCar method only throws the IllegalStateException if findById returns an empty Optional - in other words, there's no object in the repository matching the search criterion.

So in this case, the exception is never thrown, and that's what makes the test fail.

Upvotes: 1

Related Questions