bmo*_*oij 5 java static exception 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)));
}
Run Code Online (Sandbox Code Playgroud)
每次抛出 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)
Run Code Online (Sandbox Code Playgroud)
如何使用PowerMockito 从 java.nio.file.Files存根函数readAllBytes ?
调用 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));
}
Run Code Online (Sandbox Code Playgroud)
另一种可能性是:
@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));
}
Run Code Online (Sandbox Code Playgroud)
参考:使用 PowerMockito 模拟最终方法和静态方法
| 归档时间: |
|
| 查看次数: |
9303 次 |
| 最近记录: |