Home > OS >  How to throw an exception based on some condition in Junit 5?
How to throw an exception based on some condition in Junit 5?

Time:04-22

I have a spring boot application with Junit 5 and Mockito.

I have the below code.

 @Autowired
    CustomerRepo customerRepo;

    public UpdatedCustomer updateCustomer(Customer customer) {
        UpdatedCustomer updCustomer = new UpdatedCustomer();
        updCustomer.setId(customer.getId());
        //some more setters

        //Here I need to throw exceptions for the customer whose id is 5 only. Can I do this in mockito or any other framework?
        customerRepo.save(updCustomer);
        return updCustomer;
    }

I need to throw an exception for the customer whose ID is 5 in the above code and for other customers actual implementation of save should be invoked. Is it possible in SpyBean or any other way?

Kindly suggest.

CodePudding user response:

In Mockito ArgumentMatcher is a functional interface and you could use argThat matcher.

@Mock
private CustomerRepo customerRepo;

@Test
void updateCustomerThrowsException() {
    doThrow(RuntimeException.class)
            .when(customerRepo).save(argThat(customer -> customer.getId() == 5));

    var customer = new Customer();
    customer.setId(5);

    assertThrows(RuntimeException.class, () -> updateCustomer(customer));
}
  • Related