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

sk1*_*205 1 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;
    }
Run Code Online (Sandbox Code Playgroud)

下面是我的测试代码:

@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());
    }
    }
Run Code Online (Sandbox Code Playgroud)

下面是我的 UserRepository 界面:

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

public List<User> findByState(String state);
}
Run Code Online (Sandbox Code Playgroud)

当将我的测试作为 Junit 测试运行时,它给了我以下错误:

org.mockito.exceptions.base.MockitoException: 
Checked exception is invalid for this method!
Invalid: java.lang.Exception: Exception occurred
Run Code Online (Sandbox Code Playgroud)

关于如何解决这个问题的任何想法?提前致谢。

RCv*_*ram 16

如果您可以修改源代码,则使用 RuntimeException 或扩展 RuntimeException.class,如 @i.bondarekno 和 @Gayan 提到的

在某些情况下,我们无法更改源代码,这时候你可以使用mockito do应答来抛出检查异常。

 doAnswer((invocation) -> {
            throw new IOException("invalid");
        }).when(someClass).someMethodName();
Run Code Online (Sandbox Code Playgroud)


i.b*_*nko 12

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

 when(userRepository.findByState("Karnataka"))
       .thenThrow(new RuntimeException("Exception"));
Run Code Online (Sandbox Code Playgroud)