gpt4 book ai didi

java - mock java.nio.file.Paths.get 除了抛出 InvalidPathException 什么都不做

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

我有两行代码:

File file = new File("report_はな.html");
Path path = Paths.get(file.getCanonicalPath());

无论如何我可以模拟静态方法:

Paths.get(file.getCanonicalPath());

并且只抛出异常InvalidPathException?

我试过 powermockito,但它似乎不起作用

PowerMockito.mockStatic(Paths.class);
PowerMockito.doReturn(null).doThrow(new InvalidPathException("","")).when(Paths.class);

整个想法是我试图重现在英文 Mac 下的错误,Mac 默认编码设置是 US-ASCII,即 Path path = Paths.get("report_ハナ.html");将抛出此 InvalidPathException。

最佳答案

记录在案here ,您必须跳过一些环节才能模拟“系统”类,即由系统类加载器加载的类。

具体来说,在普通的 PowerMock 测试中,@PrepareForTest() 注释标识您要模拟其静态方法的类,而在“系统”PowerMock 测试中,注释需要标识要模拟的类调用静态方法(通常是被测类)。

例如,假设我们有以下类:

public class Foo {
public static Path doGet(File f) throws IOException {
try {
return Paths.get(f.getCanonicalPath());
} catch (InvalidPathException e) {
return null;
}
}
}

如果 Paths.get() 抛出 InvalidPathException,我们要测试该类是否确实返回 null。为了测试这个,我们写:

@RunWith(PowerMockRunner.class)  // <- important!
@PrepareForTest(Foo.class) // <- note: Foo.class, NOT Paths.class
public class FooTest {
@Test
public void doGetReturnsNullForInvalidPathException() throws IOException {
// Enable static mocking on Paths
PowerMockito.mockStatic(Paths.class);

// Make Paths.get() throw IPE for all arguments
Mockito.when(Paths.get(any(String.class)))
.thenThrow(new InvalidPathException("", ""));

// Assert that method invoking Paths.get() returns null
assertThat(Foo.doGet(new File("foo"))).isNull();
}
}

注意:我写了 Paths.get(any(String.class)) 但你可以模拟更多的东西如果需要,请具体说明,例如Paths.get("foo"))Paths.get(new File("report_ハナ.html").getCanonicalPath())

关于java - mock java.nio.file.Paths.get 除了抛出 InvalidPathException 什么都不做,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29319243/

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