为方法调用的每个实例返回相同的值
您好我没有使用PowerMockito而是正常的并试图模仿这样的东西:
Hi I'm not using PowerMockito but normal one and trying to mock something like this:
when(any(File.class).canWrite()).thenReturn(Boolean.FALSE)
但我得到的NullPointerException
。基本上没有模拟特定实例我想模拟文件对象的任何和所有实例返回 FALSE
for canWrite()
。
But I get a NullPointerException
. Basically without mocking a specific instance I want to mock any and all instances of a file object to return FALSE
for canWrite()
.
任何人都可以提供帮助吗?我可以模拟对象,但我正在测试的代码是在静态方法中。
Can anyone help? I can mock the object but the code I'm testing is inside a static method.
这是不可能的。对于常规的Mockito,你需要在when()调用中使用一些模拟对象,而不是任何匹配器。
This is not possible. With regular Mockito you need some mock object in the when() call, not an any matcher.
对于你的例子,当你说任何(File.class)
For your example, when you say any(File.class)
when(any(File.class).canWrite()).thenReturn(Boolean.FALSE)
您需要将一个文件对象实例化为模拟
You need to have a file object already instantiated as a Mock
File fileMock = mock(File.class);
when(fileMock.canWrite()).thenReturn(Boolean.FALSE)