單元測試進(jìn)階-跳過靜態(tài)方法
被跳過的靜態(tài)方法
example:
public class PasswordUtils {
/**
* 隨機(jī)生成 n 位包含 字母、數(shù)字、特殊字符 的密碼
*
* @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();
}
}
輸出結(jié)果為:
?文章來源地址http://www.zghlxwxcb.cn/news/detail-512418.html
跳過該靜態(tài)方法的測試:
導(dǎo)入依賴:
<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();
}
}
測試結(jié)果為:
文章來源:http://www.zghlxwxcb.cn/news/detail-512418.html
?
到了這里,關(guān)于靜態(tài)方法mock,跳過靜態(tài)方法單元測試的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!