I have a method which has the following code in it, it saves a order object to the orderStatus jpa repository and i have a try catch method which should capture the JDBC Connection exception.
How do i test this scenario using Junit and mockito?
try {
orderStatusRepository.save(newOrderStatus);
} catch (JDBCConnectionException ex) {
);
CodePudding user response:
If the code is the goal is to test that in case JDBCConnectionException is thrown it is caught and not propagated I would suggest to mock orderStatusRepository using Mockito:
when(orderStatusRepository.save(newOrderStatus))
.thenThrow(JDBCConnectionException.class);
then execute the test and check that the method returns normally and that mocked object method was accessed (the exception therefor was thrown):
verify(orderStatusRepository).save(newOrderStatus);
Note that if save
method doesn't return anything you would need to mock it a bit differently:
doThrow(JDBCConnectionException.class)
.when(orderStatusRepository).save(newOrderStatus);
CodePudding user response:
follow the below code to test your code for the JDBC connection exception.
@MockBean
private OrderStatusRepository orderStatusRepository;
@Test
public void jdbcConnectionExceptionTest() {
try{
when(orderStatusRepository.save(newOrderStatus))
.thenThrow(JDBCConnectionException.class);
orderStatusRepository.save(newOrderStatus);
} catch (Exception e) {
assertTrue(e instanceof JDBCConnectionException);
}
}