sub
sub

Reputation: 679

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

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.

Upvotes: 0

Views: 2445

Answers (2)

Rajan Singh
Rajan Singh

Reputation: 1

With Junit 5 you can use - assertThrows() to throw exception based on condition.

Example :-

@Test
public void testFooThrowsIndexOutOfBoundsException() {
    Throwable exception = assertThrows(IndexOutOfBoundsException.class, () -> foo.doStuff());
    assertEquals("expected messages", exception.getMessage());
}

Upvotes: 0

Alex
Alex

Reputation: 5982

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

Upvotes: 1

Related Questions