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 方法
- 创建mock类
- 使用
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)