Search code examples
javaspringspring-bootjunit

How to write unit test for void delete method using junit and mockito?


public void delete(Long id){
Optional<Car> optional = CarRepository.findById(id);
if(optional.isPresent()){
    Car car = optional.get();
    car.setActionStatus("DELETE");
    CarRepository.save(car);
}
else{
    throw new CustomException("custom message");
}}

I have to write a unit test for the above delete method, here we are not deleting the record instead we are just updating the setActionStatus to delete.


Solution

  • First, don't use static methods on your CarRepository, make an interface:

    interface CarRepository {
      Car findById(long id);
      void save(Car car);
      ...
    }
    

    and pass an instance of this to the class you want to test:

    class ClassToTest {
      public ClassToTest(CarRepository carRepository) { ... }
      ...
    }
    

    now in your test you can use a mock CarRepository:

    ...
    @Test
    void test() {
      // create the mocks we need and set up their behaviour
      CarRepository carRepository = mock(CarRepository.class);
      Car car = mock(Car.class);
      when(carRepository.findById(123)).thenReturn(car);
    
      // create the instance we will test and give it our mock
      ClassToTest classToTest = new ClassToTest(carRepository);
      classToTest.delete(123);
    
      // check that the expected methods were called
      verify(car).setActionStatus("DELETE");
      verify(carRepository).save(car);
    }