【问题标题】:Getting Mockito Exception : checked exception is invalid for this method获取 Mockito 异常:检查的异常对此方法无效
【发布时间】:2019-09-27 05:38:15
【问题描述】:

我有一个正在尝试测试的方法

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

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

【问题讨论】:

  • 错误信息非常具体:您的findByState 方法不能抛出Exception。特别注意(1)您应该捕获最具体的异常,在这种情况下DataAccessException,以及(2)掩盖底层异常对故障排除是有害的;确保使用采用 Throwable cause 的链式构造函数。

标签: java junit mockito checked-exceptions


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    在某些情况下,我们无法更改源代码,届时您可以使用 mockito do answer 来抛出已检查的异常。

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多