[英]Mockito: How to get the arguments passed to a method when the return type of the method is void
[英]With Mockito, how to stub a method with return type void which throws an exception when a certain argument is passed?
以下是使用异常对void方法进行存根的主要Mockito文档。 但是,Mockito doc中的示例存根无参数方法。 如果方法具有参数并且如果a参数不符合合同,则该方法抛出异常 ,该怎么办?
所以对于下面的课程......
public class UserAccountManager {
/**
* @throws Exception if user with provided username already exists
*/
public void createAccount(User user) throws Exception {
// db access code ...
}
}
...如何使用Mockito模拟 UserAccountManager.createAccount ,以便在某个User对象作为参数传递给方法时抛出异常 ?
Mockito doc已经展示了如何使用异常存根无参数 void方法的示例。
但是,对于使用参数和异常对void方法进行存根 ,请执行以下操作:
由于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));
注意eq Matcher的用法。 如果参数的类型(在本例中为User)没有自己实现equals ,您也可以尝试使用refEq Matcher。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.