静态方法mock,跳过静态方法单元测试

单元测试进阶-跳过静态方法

被跳过的静态方法

example:

public class PasswordUtils {
 /**
     * 随机生成 n 位包含 字母、数字、特殊字符 的密码
     *
     * @return
     */
    public static String randomPW(Integer count) {
        System.out.println("randomPW()");
        StringBuffer stringBuffer = new StringBuffer();
        Random random = new Random(new Date().getTime());
        String flag = type[random.nextInt(type.length)];
        // 输出长度 12 位
        int length = count;
        for (int i = 0; i < length; i++) {
            switch (flag) {
                case "word":
                    stringBuffer.append(word[random.nextInt(word.length)]);
                    break;
                case "num":
                    stringBuffer.append(num[random.nextInt(num.length)]);
                    break;
                case "symbol":
                    stringBuffer.append(symbol[random.nextInt(symbol.length)]);
                    break;
                default:
                    break;
            }
            flag= type[random.nextInt(type.length)];
        }
        return stringBuffer.toString();
    }
}

不跳过该方法的测试:

@RunWith(SpringRunner.class)
public class SysUserServiceImplTest3 {

    @InjectMocks
    private SysUserServiceImpl sysUserService;

    @Test
    public void staticTest1(){
        sysUserService.staticTest();
    }
}

输出结果为:


 

跳过该静态方法的测试:

导入依赖:

        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4</artifactId>
            <version>2.0.9</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito2</artifactId>
            <version>2.0.9</version>
            <scope>test</scope>
        </dependency>

测试代码为:

@RunWith(PowerMockRunner.class)
@PrepareForTest({PasswordUtils.class, SysUserServiceImpl.class})
public class SysUserServiceImplTest {

    @InjectMocks
    private SysUserServiceImpl sysUserService;

    @Test
    public void staticTest(){
        PowerMockito.mockStatic(PasswordUtils.class);
        PowerMockito.when(PasswordUtils.randomPW(Mockito.anyInt())).thenReturn("123");
        sysUserService.staticTest();
    }
}

测试结果为:

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值