3

私は2行のコードを持っています:

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 であるというバグを再現しようとしているということです。この InvalidPathException をスローします。

4

1 に答える 1

3

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()).

于 2016-03-21T00:29:05.663 に答える