TestNG 中 使用 PowerMock mock 方法中new的对象

 

被测试类:

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

你可能感兴趣的:(TestNG 中 使用 PowerMock mock 方法中new的对象)