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

本文介绍如何使用PowerMockito库进行文件操作的单元测试,通过模拟File类的实例,避免了实际文件系统的依赖,确保了测试的稳定性和隔离性。文章详细展示了如何设置PowerMockito来模拟File类的构造函数和exists()方法,以及如何在JUnit和TestNG环境下正确配置测试类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

被测试类:

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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

勇敢的炮灰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值