Search code examples
javaspringjunitjunit4

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

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