@Mock与@InjectMocks的区别,mock对象注入另一个mock
@Mock: 创建一个Mock.@InjectMocks: 创建一个实例,简单的说是这个Mock可以调用真实代码的方法,其余用@Mock(或@Spy)注解创建的mock将被注入到用该实例中。请注意:必须使用@RunWith(MockitoJUnitRunner.class)或Mockito.initMocks(this)初始化这些模拟并注入它们。//@RunWith(PowerMockRun...
·
@Mock: 创建一个Mock.
@InjectMocks: 创建一个实例,简单的说是这个Mock可以调用真实代码的方法,其余用@Mock(或@Spy)注解创建的mock将被注入到用该实例中。
请注意:必须使用@RunWith(MockitoJUnitRunner.class)或Mockito.initMocks(this)初始化这些模拟并注入它们。
//@RunWith(PowerMockRunner.class)
@RunWith(MockitoJUnitRunner.class)
public class RaceServiceMock {
@InjectMocks
private RaceServiceImpl raceService;
@Mock
private PriceInfoService priceInfoService;
@Test
public void testMockPub() throws Exception{
List<Map> list = new ArrayList<>();
Map map = new HashMap();
map.put("id","12");
map.put("name","zhy");
list.add(map);
//raceService = Mockito.mock(RaceServiceImpl.class); 使用mock对象,不进真实方法
Mockito.when(raceService.querySku(any())).thenReturn(list);
Mockito.verify(raceService, Mockito.times(1)).querySku(any());
Mockito.when(priceInfoService.getRealPriceInfo(any())).thenReturn("abb");
raceService.setPriceInfoService(priceInfoService); //将mock对象注入到另一个真实对象
Mockito.when(raceService.querySku(any())).thenReturn(list);
}
}
RaceServiceImpl.java
@Resource
private PriceInfoService priceInfoService;
public void setPriceInfoService(PriceInfoService priceInfoService){
this.priceInfoService = priceInfoService;
}
public List querySku(String str){
...
String res = priceInfoService.getRealPriceInfo(str);
...
}
更多推荐
所有评论(0)