代码上线前,有case覆盖率的要求,DesensUtil 类里的catch分支,没有case能覆盖,开始通过mock的方式,也走不进去,后就想通过反射的方式,把executor属性赋值为null,让报空指针错误。
executor的属性用private static final的方法修饰,通用的反射步骤会报错误:
java.lang.IllegalAccessException: Can not set static final com.alipay.dataseXXX to null。
后看google的文档解决了。
https://stackoverflow.com/questions/3301635/change-private-static-final-field-using-java-reflection
需要反射的类
public class DesensUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(DesensUtil.class);
private static final DefaultScanAndDesensExecutor executor = new DefaultScanAndDesensExecutor();
private static final DesensConfig DESENSCONFIG = new DesensConfigBuilder().appCode(CommonConstants.CLAIMCORE).build();
/**
* Scan and desens text string.
*
* @param content the content
* @return the string
*/
public static String scanAndDesensText(String content) {
try {
content = executor.scanAndDesensText(content, DESENSCONFIG);
} catch (Throwable t) {
LOGGER.error("scanAndDesensText error,but it is a weakly dependent call");
}
return content;
}
}
测试类:
@Test
public void testDesensUtil() throws Exception {
Class<?> clazz = Class.forName("com.alipay.claimcore.common.util.tools.DesensUtil");
Field field = clazz.getDeclaredField("executor");
DesensUtil desensUtil = new DesensUtil();
setFinalStatic(desensUtil ,field, null);
desensUtil.scanAndDesensText("");
}
private void setFinalStatic(Object obj, Field field, Object newValue) throws Exception {
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(obj, newValue);
}