简体   繁体   English

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

[英]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:下面是我的 UserRepository 界面:

@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:当我的测试运行为 Junit 测试时,它给了我以下错误:

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.提前致谢。

You should use RuntimeException or subclass it.您应该使用RuntimeException或将其子类化。 Your method has to declare checked exception (example: findByState(String state) throws IOException; ) otherwise use RuntimeException :您的方法必须声明已检查异常(例如: findByState(String state) throws IOException; )否则使用RuntimeException

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

According to the example provided, one should ideally look for a GenericException根据提供的示例,理想情况下应该寻找GenericException

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

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

If you can modify the source code, then use RuntimeException or extend the RuntimeException.class as @i.bondarekno and @Gayan mentioned如果您可以修改源代码,则使用 RuntimeException 或将 RuntimeException.class 扩展为@i.bondarekno 和@Gayan 提到的

In some cases, we can't change the source code, that time you can use the mockito do answer to throw checked exception.在某些情况下,我们无法更改源代码,届时您可以使用 mockito do answer to throw checked exception。

 doAnswer((invocation) -> {
            throw new IOException("invalid");
        }).when(someClass).someMethodName();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM