Getting Mockito Exception : checked exception is invalid for this method

sk17261205 picture sk17261205 · Sep 27, 2019 · Viewed 8.1k times · Source

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.

Answer

i.bondarenko picture i.bondarenko · Sep 27, 2019

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