gpt4 book ai didi

java - stub 时 PowerMockito NullPointerException

转载 作者:行者123 更新时间:2023-11-30 08:14:16 25 4
gpt4 key购买 nike

我想使用以下测试代码对 java.nio.file.Files 中的公共(public)静态函数 readAllBytes 进行 stub 。

@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 stub java.nio.file.Files 中的 readAllBytes 函数?

最佳答案

调用 Mockito,而不是 PowerMockito 并反转 stub 顺序:

@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

关于java - stub 时 PowerMockito NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29583236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com