因powermock的@PrepareForTest()注解中的Javassist与jacoco的覆盖检测机制相冲突,所以会出现覆盖率始终为0的情况。所以需要mock静态方法时,可以采用mockito3.4.0(3.4.0以上都可以)搭配jacoco进行ut测试。下面的示例仅供参考:
@RunWith(MockitoJUnitRunner.class)
public class IpUtilsTest
{
//带参数且有特殊返回值的的静态方法
@Test
public void test3() throws UnknownHostException
{
try(MockedStatic<StringUtils> mockedStatic = Mockito.mockStatic(StringUtils.class))
{
OngoingStubbing<Boolean> stubbing = mockedStatic.when(()->StringUtils.isNotBlank(ArgumentMatchers.any()));
stubbing.thenReturn(true);
String res = IpUtils.getHostAddress();
Assert.assertNull(res);
}
}
//带参数的静态方法
@Test
public void queryTest_1() throws Exception
{
try(MockedStatic<RestResponse> mockedStatic = Mockito.mockStatic(RestResponse.class))
{
mockedStatic.when(()->RestResponse.err(anyInt(