TestNGでPowerMock mockメソッドを用いたnewのオブジェクト

1670 ワード


テスト対象クラス:
public class FileTest {
    public boolean callInternalInstance(String path) {
        File file = new File(path);
        return file.exists();
    }
}

 
テスト方法:
@Test
    public void newTest() {
        File file = PowerMockito.mock(File.class);
        FileTest ft = new FileTest();
        try {
            PowerMockito.whenNew(File.class).withAnyArguments().thenReturn(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        PowerMockito.when(file.exists()).thenReturn(true);
        Assert.assertEquals(ft.callInternalInstance("abc"), true);

    }

Junitを使用する場合、@PrepareForTestは@RunWithと組み合わせて使用する必要があります https://stackoverflow.com/a/31682670/8842183
ただしtestNGを使用している場合は@RunWithコメントはありません
解決方法:
1. @PrepareForTest 注釈はテストクラスで、注釈はメソッドで無効です
2. @PrepareForTest({FileTest.class,File.class})注記パラメータではクラスを呼び出すだけでなくインスタンス化するクラスも必要です
3.テストクラス継承 PowerMockTestCase
最終テストクラス:
@PrepareForTest({FileTest.class, File.class})
public class MoattributeAssignmentApplicationTests extends PowerMockTestCase {

    @Test
    public void newTest() {
        File file = PowerMockito.mock(File.class);
        FileTest ft = new FileTest();
        try {
            PowerMockito.whenNew(File.class).withAnyArguments().thenReturn(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        PowerMockito.when(file.exists()).thenReturn(true);
        Assert.assertEquals(ft.callInternalInstance("abc"), true);

    }
}

stackoverflow: https://stackoverflow.com/a/42588580/8842183