使用PowerMockito如何对私有方法进行mock
一、介绍
最近,正在进行单元测试的补充,然后就遇到了一个令人头疼的问题;
我有一个publicMethod
方法,在当中调用了privateMethod
方法。
我需要对publicMethod
方法进行测试,但我不想测试privateMethod
方法。
这单测该怎么写???
二、代码
需要测试的类与方法
代码语言:javascript复制package com.banmoon.service.impl;
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 {
@Override
public void publicMethod(String name) {
log.info("公共方法:{}", name);
privateMethod(name);
}
private void privateMethod(String name) {
log.info("私有方法:{}", name);
}
}
可以看到publicMethod
方法调用了privateMethod
,也就是公共方法调用了私有方法。
我们需要对私有方法进行mock
package com.banmoon.powerMockitoTest;
import com.banmoon.service.impl.PowerMockitoServiceImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.mockito.ArgumentMatchers.anyString;
/**
* @author banmoon
* @date 2024/07/15 18:09:02
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest(PowerMockitoServiceImpl.class)
public class PublicCallPrivateMethodTest {
@InjectMocks
private PowerMockitoServiceImpl powerMockitoServiceImplUnderTest;
@Test
public void testPublicMethod() throws Exception {
// 设置参数
powerMockitoServiceImplUnderTest = PowerMockito.spy(powerMockitoServiceImplUnderTest);
PowerMockito.doNothing()
.when(powerMockitoServiceImplUnderTest, PowerMockito.method(PowerMockitoServiceImpl.class, "privateMethod", String.class))
.withArguments(anyString());
// 运行测试
powerMockitoServiceImplUnderTest.publicMethod("name");
// 验证结果
PowerMockito.verifyPrivate(powerMockitoServiceImplUnderTest).invoke("privateMethod", anyString());
}
}
三、最后
注意一下,断言的位置是使用了PowerMockito.verifyPrivate()
,可以对私有方法进行次数的断言