0


静态方法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();
    }
}

测试结果为:


本文转载自: https://blog.csdn.net/yuxue0824/article/details/127863733
版权归原作者 南柯一梦' 所有, 如有侵权,请联系我们删除。

“静态方法mock,跳过静态方法单元测试”的评论:

还没有评论