【问题标题】:thenThrow() not throwing an exceptionthenThrow() 不抛出异常
【发布时间】:2021-02-04 12:29:00
【问题描述】:

我在OneServiceImpl 类中有一个方法,如下所示。在那个类中,我从另一个类调用接口方法。

public class OneServiceImpl {
    //created dependency
    final private SecondService secondService;
            
    public void sendMessage(){
        secondService.validateAndSend(5)
    }
            
}

public interface SecondService() {

    public Status validateAndSend(int length);
}
        
public class SecondServiceImpl {
        
    @Override
    public Status ValidateAndSend(int length) {
        if(length < 5) {
            throw new BadRequestException("error", "error");
        }
    }
}

现在,当我尝试对 OneServiceImpl 执行单元测试时,我无法抛出 BadRequestException

when(secondService.validateAndSend(6)).thenThrow(BadRequestException.class);

【问题讨论】:

    标签: spring-boot junit mockito


    【解决方案1】:

    不太确定您的用例是什么,但我认为您应该编写自己的测试来接受和测试异常。

    @Test(expected = BadRequestException.class)
    public void testValidateAndSend(){
        SecondService secondService = new SecondService();
        secondservice.ValidateAndSend(6); //method should be lowercase
    }
    

    【讨论】:

      【解决方案2】:

      考虑到您没有发布代码+单元测试的完整示例,不确定是否是这种情况,但是只有当您将6 作为参数传递时,您的模拟才会抛出。使用 when 配置模拟行为时,您会告诉它仅在使用参数 6 调用 validateAndSend 方法时抛出。

      when(secondService.validateAndSend(6)).thenThrow(...)
      

      在您的代码中,您有 5 硬编码。所以这个模拟永远不会抛出你拥有的代码,因为它被配置为对带有参数6 的调用做出反应,但实际代码总是通过5 调用它。

      public void sendMessage(){
          secondService.validateAndSend(5)
      }
      

      如果传递给模拟的值不重要,您可以执行以下操作,无论传递给它什么都会抛出:

      when(secondService.validateAndSend(any())).thenThrow(BadRequestException.class);
      

      另一方面,如果值很重要并且必须是 5,您可以使用以下命令更改模拟的配置:

      when(secondService.validateAndSend(5)).thenThrow(BadRequestException.class)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-24
        • 2013-05-24
        • 2010-12-09
        • 2015-12-13
        • 2021-11-21
        相关资源
        最近更新 更多