junit mock system class 系统类(boostrap loader类)

sto例子

如何mock系统类
给出了下面例子。把SystemUtils改成系统类System也是一样的,而且@PrepareForTest不用加System.class

package sample.com.sample_app;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static junit.framework.TestCase.assertEquals;

@RunWith(PowerMockRunner.class)
@PrepareForTest({SystemUtils.class})
public class FileUtilsTest {

    @Test
    public void generateName() {
        PowerMockito.spy(SystemUtils.class);
        PowerMockito.when(SystemUtils.currentTimeMillis()).thenReturn(100L);

        String name = FileUtils.generateName();
        assertEquals("100", name);
    }
}

System

要添加

@RunWith(PowerMockRunner.class)

如果是系统类,不用添加到@PrepareForTest中,否则要添加
然后mock静态类

@Before
    public void setup() {
        PowerMockito.mockStatic(Files.class);  // 1
    }

然后在test方法里设置返回值

PowerMockito.when(System.currentTimeMillis()).thenReturn(999L);
System.out.println(System.currentTimeMillis());

Files实例

Files的案例,如下图

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值