假设我们有一个配置获取的方法
ConstService.getValue("project", "key");
getValue是个static method,那如何对static method进行mock呢,假设现在FuncService中的funcC会调用getValue获取一个配置值
@Service
public class FuncService implements IFuncServcie {
public String funcC(final Long userId) throws Exception {
// userId=0,我们获取配置值
if (userId == 0) {
return ConstService.getValue("project", "key");
}
return "";
}
}
现在我们改进一下测试代码
class FuncTest {
@Spy
@InjectMocks
private IFuncService funcService = PowerMockito.spy(new FuncService());
@Test
void funcCUT() {
final String VALUE = "1";
//声明我们需要mock的类
PowerMockito.mockStatic(ConstService.class);
PowerMockito
.doReturn(VALUE)
.when(ConstService.class, "getValue", Mockito.anyString(), Mockito.anyString());
Assertions.assertEquals(
VALUE,
PrivateAccessor.invoke(funcService, "funcC", 0)
);
}
}
这里并不关心getValue的入参,如果你希望指定参数,则可以修改Mockito.anyString()为你指定的参数,如果需要针对不同的入参进行不同的返回,可以使用doAnswer进行处理,然后记得要在PrepareForTest加入被mock的类