简体   繁体   English

为方法调用的每个实例返回相同的值

[英]Return same value for every instance of a method call

Hi I'm not using PowerMockito but normal one and trying to mock something like this: 嗨,我不是使用PowerMockito,而是普通的并尝试模拟如下内容:

when(any(File.class).canWrite()).thenReturn(Boolean.FALSE)

But I get a NullPointerException . 但是我得到了NullPointerException Basically without mocking a specific instance I want to mock any and all instances of a file object to return FALSE for canWrite() . 基本上不模拟特定实例,我想模拟文件对象的所有实例以为canWrite()返回FALSE

Can anyone help? 有人可以帮忙吗? I can mock the object but the code I'm testing is inside a static method. 我可以模拟对象,但是我正在测试的代码在静态方法中。

This is not possible. 这是不可能的。 With regular Mockito you need some mock object in the when() call, not an any matcher. 使用常规的Mockito,在when()调用中需要一些模拟对象,而不是任何匹配器。

For your example, when you say any(File.class) 例如,当您说出any(File.class)

when(any(File.class).canWrite()).thenReturn(Boolean.FALSE)

You need to have a file object already instantiated as a Mock 您需要具有已实例化为Mock的文件对象

File fileMock = mock(File.class);    
when(fileMock.canWrite()).thenReturn(Boolean.FALSE)

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

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