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;
}
}
}
がスローされたnull
場合、このクラスが実際に返されることをテストしたいと思います。これをテストするために、次のように記述します。Paths.get()
InvalidPathException
@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())
.