简体   繁体   English

Mockito 测试 void 方法抛出异常

[英]Mockito test a void method throws an exception

I have a method with a void return type.我有一个返回类型为void的方法。 It can also throw a number of exceptions so I'd like to test those exceptions being thrown.它也可以抛出一些异常,所以我想测试那些抛出的异常。 All attempts have failed with the same reason:所有尝试都失败了,原因相同:

The method when(T) in the type Stubber is not applicable for the arguments (void)类型 Stubber 中的方法 when(T) 不适用于参数 (void)

Any ideas how I can get the method to throw a specified exception?有什么想法可以让方法抛出指定的异常吗?

doThrow(new Exception()).when(mockedObject.methodReturningVoid(...));

The parentheses are poorly placed.括号位置不好。

You need to use:你需要使用:

doThrow(new Exception()).when(mockedObject).methodReturningVoid(...);
                                          ^

and NOT use:并且使用:

doThrow(new Exception()).when(mockedObject.methodReturningVoid(...));
                                                                   ^

This is explained in the documentation这在文档中进行了解释

If you ever wondered how to do it using the new BDD style of Mockito:如果你想知道如何使用新的 BDD 风格的 Mockito 来做到这一点:

willThrow(new Exception()).given(mockedObject).methodReturningVoid(...));

And for future reference one may need to throw exception and then do nothing:为了将来参考,可能需要抛出异常然后什么也不做:

willThrow(new Exception()).willDoNothing().given(mockedObject).methodReturningVoid(...));

You can try something like the below:您可以尝试以下方法:

 given(class.method()).willAnswer(invocation -> {
          throw new ExceptionClassName();
        });
    

In my case, I wanted to throw an explicit exception for a try block,my method block was something like below就我而言,我想为 try 块抛出一个显式异常,我的方法块如下所示

     public boolean methodName(param) throws SomeException{
    
        try(FileOutputStream out = new FileOutputStream(param.getOutputFile())) {
          //some implementation
        } catch (IOException ioException) {
          throw new SomeException(ioException.getMessage());
        } catch (SomeException someException) {
          throw new SomeException (someException.getMessage());
        } catch (SomeOtherException someOtherException) {
          throw new SomeException (someOtherException.getMessage());
        }
        return true;
      }

I have covered all the above exceptions for sonar coverage like below我已经涵盖了上述所有声纳覆盖的例外情况,如下所示

   given(new FileOutputStream(fileInfo.getOutputFile())).willAnswer(invocation -> {
      throw new IOException();
    });
    Assertions.assertThrows(SomeException.class, () ->
    {
      ClassName.methodName(param);
    });

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

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