mock单元测试

mock static方法

  1. 仅有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); // 返回值类型强转即可
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值