存根时PowerMockito NullPointerException

时间:2015-04-11 21:25:46

标签: java exception static powermockito

我想使用以下测试代码从java.nio.file.Files中存根公共静态函数 readAllBytes

@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)

如何使用PowerMockito从java.nio.file.Files中存储函数 readAllBytes

3 个答案:

答案 0 :(得分:1)

致电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));
   }

参考:Using PowerMockito to Mock Final and Static Methods

答案 1 :(得分:0)

确保在@PrepareForTest中包含调用静态方法的类。

@PrepareForTest({Files.class, ClassThatCallsFiles.class})

答案 2 :(得分:0)

请在 pom.xml 中添加此依赖项,同时为静态方法模拟文件类。

<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-core</artifactId>
    <version>2.0.9</version>
    <scope>test</scope>
</dependency>

这也是您收到 NullPointerException 的因素之一