[英]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.