使用PowerMockito如何对私有方法进行单元测试

2024-07-16 10:12:35 浏览数 (3)

使用PowerMockito如何对私有方法进行单元测试

一、介绍

在上一篇文章中,讲解了公共方法调用私有方法的测试,我们只想对公共方法进行验证测试,私有方法进行mock即可

那么在本篇中,如何对私有方法进行单元测试呢?

二、代码

需要测试的类与私有方法,仅贴出关键代码,实体类什么的就没必要贴了

代码语言:javascript复制
package com.banmoon.service.impl;
​
import com.banmoon.mapper.PowerMockitoMapper;
import com.banmoon.service.PowerMockitoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
​
@Slf4j
@Service
@RequiredArgsConstructor
public class PowerMockitoServiceImpl implements PowerMockitoService {
​
    private final PowerMockitoMapper powerMockitoMapper;
​
    private void privateMethodNeedTest() {
        PowerMockitoEntity entity = new PowerMockitoEntity();
        entity.setId(1);
        entity.setValue("1");
        entity.setStatus(true);
        powerMockitoMapper.updateById(entity);
    }
​
}

那么这个单测也很简单,只需要这样

代码语言:javascript复制
package com.banmoon.powerMockitoTest;
​
import com.banmoon.mapper.PowerMockitoMapper;
import com.banmoon.service.impl.PowerMockitoServiceImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.modules.junit4.PowerMockRunner;
​
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
​
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
​
/**
 * @author banmoon
 * @date 2024/07/15 19:41:37
 */
@RunWith(PowerMockRunner.class)
public class PrivateMethodNeedTest {
​
    @Mock
    private PowerMockitoMapper powerMockitoMapper;
​
    @InjectMocks
    private PowerMockitoServiceImpl powerMockitoServiceImplUnderTest;
​
    @Test
    public void testPrivateMethodNeedTest() throws InvocationTargetException, IllegalAccessException {
        // 设置参数
        PowerMockito.when(powerMockitoMapper.updateById(any())).thenReturn(1);
​
        // 运行测试
        Method testMethod = PowerMockito.method(PowerMockitoServiceImpl.class, "privateMethodNeedTest");
        testMethod.invoke(powerMockitoServiceImplUnderTest);
​
        // 验证结果
        verify(powerMockitoMapper).updateById(any());
    }
​
}

可以看到,在运行测试那个地方,使用了反射来执行了私有方法。

正所谓,遇事不决,反射解决

3)最后

后面找找有没有更加好用的工具类来完成这种单元测试。

0 人点赞