获取 Mockito 异常:已检查的异常对于此方法无效
2022-09-03 17:40:41
我有一个我正在尝试测试的方法
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());
}
}
以下是我的用户存储库界面:
@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
关于如何解决这个问题的任何想法?提前致谢。