mock static方法
- 仅有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 @value() 和private方法
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/spring-config-*.xml"})
public class ServiceImplTest {
@InjectMocks
private ServiceImpl service;
@Before
public void initValue() {
// 注入ServiceImpl 中的
// @Value("#{'${biztype.set}'.split(',')}")
// private Set<Integer> bizTypeSet;
MockitoAnnotations.initMocks(this);
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3));
ReflectionTestUtils.setField(service, "bizTypeSet", set);
}
@Test
public void privateMethodTest() throws Throwable {
Map<String, Request> parm1 = new HashMap<>(); // 此为方法入参1
Map<String, Request> parm2 = new HashMap<>(); // 此为方法入参2
// 使用反射调用私有方法
Class<?>[] parameterTypes = {Map.class,List.class}; // 此为方法入参类型
java.lang.reflect.Method privateMethod = ServiceImpl.class.getDeclaredMethod("privateMethodName", parameterTypes);
privateMethod.setAccessible(true);
List<List<Long>> result = (List<List<Long>>) privateMethod.invoke(service, parm1,parm2); // 返回值类型强转即可
}
}