【问题标题】:Using mockito to test methods which throw uncaught custom exceptions使用 mockito 测试抛出未捕获的自定义异常的方法
【发布时间】:2012-02-11 07:51:27
【问题描述】:

如何编写基于 Mockito 的 JUnit 方法来测试此方法 adduser()?我试着写一个,但它失败了,错误信息说异常没有被处理。错误显示为:

when(service.addUser("nginx")).thenReturn("apache");

假设业务类中的addUser() 方法从不捕获任何异常并且未完成重新抛出。

class Business {
    public User addUser() throws ServiceException{
        User user = service.addUser("nginx");
        return user;
    }
}

测试用例方法:

在测试类中,我使用@Mock 属性模拟服务层类并注入它。

@Mock
Service service;   

@InjectMocks
Business business = new Business();

@Test
public void testAddUser() {
    when(service.addUser("nginx")).thenReturn("apache");    
    User user = business.addUser("nginx");
    assertNotNull(user);
}

请告诉我如何处理测试用例中的异常场景。

【问题讨论】:

  • 您是否知道您正在测试的只是该方法返回的内容不为空。我认为您应该断言它返回“apache”,因为您确实需要检查 service.addUser() 是否已被实际调用。

标签: java mockito custom-exceptions


【解决方案1】:

在测试方法中声明异常。

public void testAddUser() throws ServiceException {
...
}

【讨论】:

  • 我有一个方法可以抛出 11 个不同的异常(它是第 3 方依赖项),所以抛出的异常列表变得非常长。有什么办法可以避免吗?
  • 我已经养成了在所有 JUnit 方法上只写 throws Exception 的习惯。实际上没有理由不这样做,因为 JUnit 框架会捕获并报告您没有捕获的任何内容。 @Olov
猜你喜欢
  • 2013-02-15
  • 1970-01-01
  • 1970-01-01
  • 2015-07-14
  • 2023-03-18
  • 1970-01-01
  • 2023-01-25
  • 2021-10-28
相关资源
最近更新 更多