概述
- 仅有static方法
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
@PrepareForTest({SpringContextUtil.class})
@PowerMockIgnore({"javax.management.*"})
public class ConditionServiceImplTest{
@Before
public void initExecutor(){
PowerMockito.mockStatic(SpringContextUtil.class);
PowerMockito.when(SpringContextUtil.getBean(Mockito.anyString())).thenReturn(new ThreadPoolTaskExecutor());
}
}
2.带有static代码块
无法mock static{}代码块, 所以需要手动初始化内容
public class WorkersUtils {
private static WorkerType workerType;
static {
String workerTypeStr = PropertiesUtils.getValueByKey(Constants.WORKETYPE);
String[] workerTypeArray = workerTypeStr.split(",");
WorkersUtils.workerType = new WorkerType(Boolean.valueOf(workerTypeArray[3]));
}
public static WorkerType getWorkerType(){
return workerType;
}
/**
* 是否预发布的日志前缀
* @return
*/
public static String getWorkerTypeLogPrefix(){
return workerType.isYfb() ? "[预发布]" : "";
}
}
public class WorkerType {
public WorkerType(boolean isYfb){
this.isYfbWorker = isYfb;
}
/**
* 是否是预发布
*/
private boolean isYfb;
}
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
@PrepareForTest({WorkersUtils.class})
@PowerMockIgnore({"javax.management.*"})
@SuppressStaticInitializationFor("com.xxx.util.WorkersUtils")
public class ConditionServiceImplTest{
@Before
public void init(){
WorkerType workerType = new WorkerType(false);
PowerMockito.mockStatic(WorkersUtils.class);
PowerMockito.when(WorkersUtils.getWorkerType()).thenAnswer(t->workerType);
PowerMockito.when(WorkersUtils.getWorkerTypeLogPrefix()).thenAnswer(t->"");
}
}
最后
以上就是拉长咖啡为你收集整理的Mock带有static方法的全部内容,希望文章能够帮你解决Mock带有static方法所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复