PowerMockito 使用方法

PowerMockito 是 Mockito 的增强版, 可以调用static,final,private 修饰的方法。

when().thenReturn()

eg:

Instance instance = new Instance();
instance.setExpiredTime(new Date(100));
when(instanceDao.getInstanceWithId(anyString())).thenReturn(instance);

补充,如果需要连续调用方法,在mock对象时,加入参数RETURNS_DEEP_STUBS

Map<String, Object> map = new HashMap<>();
List<DictItemBean> listMock = mock(List.class, RETURNS_DEEP_STUBS);
when(listMock.stream().collect(any())).thenReturn(map);

doReturn().when()

该方法是when().thenReturn()的变式,两者的区别:http://sangsoonam.github.io/2019/02/04/mockito-doreturn-vs-thenreturn.html

doNothing().when().getmethod()

当函数的返回值为null时,使用该方法

//redisHelper.serForValue(String, String) 返回值为null
doNothing().when(redisHelper).setForValue(anyString(), anyString());

PowerMockito 各种调用方法

普通 public 方法

  1. 创建mock类
  2. 使用doReturn().when()when().thenReturn() mock 相关方法

@Mock 是mock该类,即该类的所有方法都被mock,返回对应的默认值(或null)
@Spy 并不是mock该类,该类仍然为真实的类。 只有在mock特定方法后,该mock方法会返回指定值,其他为mock的方法仍是真实的方法

注意:对于Mock注入的类需要spy时,不要在@InjectMock上面再加上@Spy, 这样是无法spy该类的。

正确的方法:将@InjectMock 类再进行 spy
MonitorMetricServiceImpl spy = spy(monitorMetricService);

public class MonitorMetricServiceImplTest {

    Logger log = LoggerFactory.getLogger(MonitorMetricServiceImplTest.class);

    @InjectMocks
    MonitorMetricServiceImpl monitorMetricService;

    @Mock
    InstanceDao instanceDao;
    @Mock
    RestTemplate restTemplate;
    @Mock
    RefreshRedis refreshRedis;
    @Test
    public void getMetrics() throws Exception{
    	//spy injectMock类
        MonitorMetricServiceImpl spy = spy(monitorMetricService);
        PowerMockito.doNothing().when(spy, "getInstanceStatus", any());
        PowerMockito.doNothing().when(spy, "getServiceStatus", any());
        spy.getMetrics();
    }
}

被 mock 的类

public class InstanceService {
    
    private String id;
    
    public String getId(){
        return id;
    }
    
    public void setId(String id){
        this.id = id;
    }
    
}

测试方法

public class TestMockTestClass {

    @Spy
    TestMockClass testMock;

    @Test
    public void getId(){
    	//这两种方法都可
        doReturn("Mock").when(testMock).getId();
//      when(instanceService.getId()).thenReturn("Mock");
        System.out.println(testMock.getId());
    }
}

@RunWith(MockitoJUnitRunner.class)
@RunWith(PowerMockRunner.class)

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值