我想用下面的测试代码从readAllBytes中存根java.nio.file.Files的公共静态函数。
@PrepareForTest(Files.class)
public void testGetNotExistingRestFile() throws Exception {
PowerMockito.mockStatic(Files.class);
PowerMockito.doThrow(mock(IOException.class)).when(Files.readAllBytes(any(Path.class)));
}每次抛出一个NullPointerException时,我都能找出我做错了什么。
java.lang.NullPointerException
at java.nio.file.Files.provider(Files.java:67)
at java.nio.file.Files.newByteChannel(Files.java:317)
at java.nio.file.Files.newByteChannel(Files.java:363)
at java.nio.file.Files.readAllBytes(Files.java:2981)
at nl.mooij.bob.RestFileProviderTest.testGetNotExistingRestFile(RestFileProviderTest.java:53)如何用readAllBytes从java.nio.file.Files中存根函数PowerMockito?
发布于 2015-09-18 02:26:54
调用Mockito,而不是PowerMockito,并颠倒固执顺序:
@Test(expected=IOException.class)
@PrepareForTest(Files.class)
public void testGetNotExistingRestFile() throws Exception {
// arrange
PowerMockito.mockStatic(Files.class);
Mockito.when(Files.readAllBytes(Matchers.any(Path.class))).thenThrow(Mockito.mock(IOException.class));
// act
Files.readAllBytes(Mockito.mock(Path.class));
}另一种可能是:
@Test(expected=IOException.class)
@PrepareForTest(Files.class)
public void testGetNotExistingRestFile() throws Exception {
// arrange
PowerMockito.mockStatic(Files.class);
Files filesMock = PowerMockito.mock(Files.class);
Mockito.when(filesMock.readAllBytes(Matchers.any(Path.class))).thenThrow(Mockito.mock(IOException.class));
// act
filesMock.readAllBytes(Mockito.mock(Path.class));
}参考资料:用PowerMockito模拟最终方法和静态方法
发布于 2017-05-23 00:22:55
确保包含在@PrepareForTest中调用静态方法的类。
@PrepareForTest({Files.class, ClassThatCallsFiles.class})发布于 2021-03-23 11:30:10
在为静态方法模拟Files类时,请在pom.xml中添加此依赖项。
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-core</artifactId>
<version>2.0.9</version>
<scope>test</scope>
</dependency>这也是您获得NullPointerException的一个因素。
https://stackoverflow.com/questions/29583236
复制相似问题