Search code examples
javajunitmockitochecked-exceptions

Getting Mockito Exception : checked exception is invalid for this method


I have a method which I am trying to test

public List<User> getUsers(String state) {

        LOG.debug("Executing getUsers");

        LOG.info("Fetching users from " + state);
        List<User> users = null;
        try {
            users = userRepo.findByState(state);
            LOG.info("Fetched: " + mapper.writeValueAsString(users));
        }catch (Exception e) {
            LOG.info("Exception occurred while trying to fetch users");
            LOG.debug(e.toString());
            throw new GenericException("FETCH_REQUEST_ERR_002", e.getMessage(), "Error processing fetch request");
        }
        return users;
    }

Below is my test code:

@InjectMocks
    private DataFetchService dataFetchService;

    @Mock
    private UserRepository userRepository;

@Test
    public void getUsersTest_exception() {
        when(userRepository.findByState("Karnataka")).thenThrow(new Exception("Exception"));
        try {
            dataFetchService.getUsers("Karnataka");
        }catch (Exception e) {
            assertEquals("Exception", e.getMessage());
    }
    }

Below is my UserRepository interface:

@Repository
public interface UserRepository extends CrudRepository<User, Integer> {

public List<User> findByState(String state);
}

When the run my test as Junit test, it gives me following error:

org.mockito.exceptions.base.MockitoException: 
Checked exception is invalid for this method!
Invalid: java.lang.Exception: Exception occurred

Any idea on how to resolve this? Thanks in advance.


Solution

  • You should use RuntimeException or subclass it. Your method has to declare checked exception (example: findByState(String state) throws IOException;) otherwise use RuntimeException:

     when(userRepository.findByState("Karnataka"))
           .thenThrow(new RuntimeException("Exception"));