'Test a method that use a spring service

I have a problem testing a method in Java (I use jUnit 4) and this method to test make a call to a repository and should throw an exception if something is wrong, the method looks like:

//Method located in a Spring service and use a repository to make the query
public void updateCustomer(CustomerEntity customer) throws CustomException {
        try {
            getDataDao().update(customer);
        } catch (Exception e) {
            throw new CustomException(e.getMessage());
        }
    }

The question is, How can I make for the test case enter the catch block and throw the exception? I am setting the customer to null but don't work.

Thanks for your help.



Solution 1:[1]

You need to mock that DAO call and throw and exception from there.

You will get more idea about @Mock, @InjectMock and @Mockito framework here.

  Mockito.when(getDataDao().update(any()))
      .thenThrow(Exception.class);

Solution 2:[2]

You can achieve this using the mockito framework.If you are an absolute beginner for this framework ,then I recommend you to refer the following tutorials. Mockito - Exception Handling

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sagar Gangwal
Solution 2 Hasindu Dahanayake