单元测试进阶-跳过静态方法
被跳过的静态方法
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();
}
}
输出结果为:
文章来源地址https://www.toymoban.com/news/detail-512418.html
跳过该静态方法的测试:
导入依赖:
<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://www.toymoban.com/news/detail-512418.html
到了这里,关于静态方法mock,跳过静态方法单元测试的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!