获取Mockito异常:此方法的检查异常无效

时间:2019-09-27 05:38:15

标签: java junit mockito checked-exceptions

我有一种要尝试的方法

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

下面是我的测试代码:

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

下面是我的UserRepository界面:

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

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

将我的测试作为Junit测试运行时,会出现以下错误:

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

关于如何解决此问题的任何想法?预先感谢。

2 个答案:

答案 0 :(得分:1)

您应该使用RuntimeException或对其进行子类化。您的方法必须声明已检查的异常(例如:findByState(String state) throws IOException;),否则请使用RuntimeException

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

答案 1 :(得分:0)

根据提供的示例,理想情况下应该寻找GenericException

when(userRepository.findByState("Karnataka")).thenThrow(RuntimeException.class);

GenericException exception = assertThrows(GenericException.class, () -> 
                                       userRepository.findByState("Karnataka"));