单元测试进阶-跳过静态方法
被跳过的静态方法
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();
}
}
测试结果为:
版权声明:本文为yuxue0824原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。