@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);
    	...
}
Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐