0

In my Spring boot app I want to write a test to assert SQLIntegrityConstraintViolationException

    @Test
    public void deleteCar_whenIntegrityConstraintViolationException()
    {
        doThrow( new SQLIntegrityConstraintViolationException() ).when( carRepository ).deleteCar( anyInt() );
        CustomResponse response = carService.deleteCar( 5 );
        Assert.assertEquals( "unsuccessful", response.getStatus() );
    }


I have set CustomResonse to be unsuccessful when Exception occurred.

but the problem is Mockito don't allow me to test arbitrary exception as mentioned in this stack answer

If you really want to do this, then have Mockito throw a new RuntimeException() or even better throw a new ArrayIndexOutOfBoundsException() since the API specifies that that is the only valid Exception to be thrown.

is there any other way to test this SQLIntegrityConstraintViolationException ?.

Bawantha
  • 3,644
  • 4
  • 24
  • 36

1 Answers1

0

in case u use JUnit4 add new line in test method that using when()

when(carRepository.deleteCar(5)).thenThrow(SQLIntegrityConstraintViolationException.class);
LunaLissa
  • 45
  • 3
  • same error org.mockito.exceptions.base.MockitoException: Checked exception is invalid for this method! Invalid: java.sql.SQLIntegrityConstraintViolationException – Bawantha Jun 10 '21 at 07:10
  • you cannot throw a checked exception from a method that doesnt declare it. Probably you should throw a DataAccessException (which is aRuntimeException from spring). take a look at: https://stackoverflow.com/questions/54035808/how-to-handle-the-sqlintegrityconstraintviolationexception-in-spring-boot – benebo22 Jun 10 '21 at 08:27