mock java.nio.file.Paths.get除了抛出InvalidPathException之外什么都不做
我有两行代码:mock java.nio.file.Paths.get除了抛出InvalidPathException之外什么都不做,java,encoding,jvm,powermockito,Java,Encoding,Jvm,Powermockito,我有两行代码: File file = new File("report_はな.html"); Path path = Paths.get(file.getCanonicalPath()); 我是否可以模拟静态方法: Paths.get(file.getCanonicalPath()); 只抛出异常InvalidPathException 我试过powermockito,但似乎不起作用 PowerMockito.mockStatic(Paths.class); PowerMockito.do
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,路径=Paths.get(“报告”)_はな.html);;将抛出此InvalidPathException。如文件所述,您必须跳过一些环来模拟“系统”类,即由系统类加载器加载的类
具体地说,在普通的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;
}
}
}
我们想测试一下,如果path.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();
}
}
@RunWith(PowerMockRunner.class)//只是猜测,但通过实现自定义的文件系统