[英]any(object.class) throwing null in mockito
我有以下課程:
mockStatic(Exception.class);
PowerMockito.doNothing().when(Exception.class);
Exception.throwErrorIfExists(any(Object.class)); // line3
在異常類中,方法定義如下:
static void throwErrorIfExists(def model){
if(model.hasErrors())
throwError(model)
}
第3行引發以下異常: Cannot invoke method hasErrors() on null object java.lang.NullPointerException: Cannot invoke method hasErrors() on null object
在任何情況下any(object.class)
如何都可以為NULL,因為any僅僅意味着返回任何東西?
調用方法(hasErrors()時,不能使用null參數調用ThrowErrorIfExists。這與任何模擬都沒有關系,但這只是方法中的錯誤。
您使用匹配器來調用方法
Exception.throwErrorIfExists(any(Object.class));
這很奇怪; 匹配器用於配置模擬行為,例如
PowerMockito.doNothing().when(Exception.throwErrorIfExists(any(Object.class)));
然后,您可以使用任何對象調用throwErrorIfExists來觸發“不執行任何操作”。
我認為您正在濫用any()
方法。 該方法存在,因此您可以驗證與模擬的交互,例如,您可以說:
// checks yourMethod() was invoked with any argument
verify(mockedObject).yourMethod(any(SomeClass.class));
如果要使用任意對象調用方法,則應在測試中創建對象並將其傳遞any()
並非只是為您創建對象的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.