Home > Software engineering >  How to write unit test for void delete method using junit and mockito?
How to write unit test for void delete method using junit and mockito?

Time:09-24

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.

CodePudding user response:

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

CodePudding user response:

Don't use static repositories like CarRepository. Static method are difficult to mock. Use non-static methods and inject the instance of CarRepository using dependency injection. Then you can easily inject a mock object instead.

If you insist on using static methods, there are other solutions like PowerMock library. But I wouldn't recommend it.

See also: Why doesn't Mockito mock static methods?

  • Related