java 使用 Mockito,如何存根返回类型为 void 的方法,该方法在传递某个参数时会引发异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15682631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:29:50  来源:igfitidea点击:

With Mockito, how to stub a method with return type void which throws an exception when a certain argument is passed?

javaunit-testingjunitmockito

提问by rmoestl

Here is the principal Mockitodocumentation for stubbing void methods with exceptions. However, the example in the Mockito doc stubs a parameterlessmethod. What if the method has parametersand the method throws an Exceptionif the a parameter does not fulfills the contract?

这是用于存根 void 方法的主要Mockito文档和异常。但是,Mockito 文档中的示例存根了一个无参数方法。如果方法有参数,如果 a 参数不满足约定,方法会抛出异常怎么办?

So for the following class...

所以对于接下来的课程......

public class UserAccountManager {    
   /**
    * @throws Exception if user with provided username already exists
    */
    public void createAccount(User user) throws Exception {
        // db access code ...
    }
}

... how can UserAccountManager.createAccount be mockedwith Mockitoso that it throws an Exceptionif a certain User object is passedas an argument to the method?

...如何UserAccountManager.createAccount被模拟的Mockito使得其抛出异常,如果一个特定的用户对象被传递作为参数的方法?

回答by rmoestl

The Mockito docalready shows an example of how to stub a parameterlessvoid method with exceptions.

所述的Mockito文档已经示出了如何存根的示例性参数的例外空隙方法。

However, for stubbing a void method with parameters and exceptions, do this:

但是,要使用参数和异常存根 void 方法,请执行以下操作:

Since the return type of createAccount is void, you have to use doThrow:

由于createAccount返回类型是 void,您必须使用doThrow

User existingUser = ... // Construct a user which is supposed to exist
UserAccountManager accountMng = mock(UserAccountManager.class);    

doThrow(new Exception()).when(accountMng).createAccount(eq(existingUser));

Note the usage of the eqMatcher. If the argument's type (in this case User) does not implement equalson its own you can also try to use the refEqMatcher.

注意eqMatcher的用法。如果参数的类型(在本例中为 User)本身没有实现equals,您也可以尝试使用refEqMatcher。