Mockito和嵌套的方法调用问题,怎么解决
发布网友
发布时间:2022-04-22 14:46
我来回答
共1个回答
热心网友
时间:2023-10-18 20:45
Jmock和Mockito是常用的mock工具,Jmock功能相当强大,也比较容易用。Mockito 在处理多层嵌套时比较麻烦,下面说明了这种场景的主要用法。不过建议不是用jmock。
package com.jd.test;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.when;
import javax.annotation.Resource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.jd.test.service.CustomerBusiness;
import com.jd.test.service.FeeBusiness;
import com.jd.test.service.OrderBusiness;
import com.jd.test.service.ProctBusiness;
import com.jd.test.service.impl.FeeBusinessImpl;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/spring-config.xml")
public class MockitoTest {
@Resource
@InjectMocks
private ProctBusiness injectProctBusiness;
@Mock
private OrderBusiness orderBusiness;
@Resource
@InjectMocks
private CustomerBusiness customerBusiness;
@Spy
private FeeBusiness feeBusiness = new FeeBusinessImpl();
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
/**
* 自动注入mock管理的bean. 解决二层和多层bean嵌套的部分mock场景。即injectProctBusiness->customerBusiness->feeBusiness 时,如果想mock feeBusiness中的某个方法.
*
* @Resource
@InjectMocks
private ProctBusiness injectProctBusiness;
@Resource
@InjectMocks
private CustomerBusiness customerBusiness;
@Spy
private FeeBusiness feeBusiness = new FeeBusinessImpl();
*
* @InjectMocks 标签会自动填充带@Spy和@Mock标签的bean.
* @Spy 被它代理的bean,默认执行原生方法。但可以在后期mock想要的方法。
* @Mock 相当于mockito帮助简单的实例化bean,因此无法执行原生方法。适用于整个bean都mock,如DAO。
*
* 同时可以结合spring一起管理bean.对bean的管理应该是spring先进行一系列的如初始化bean操作,然后mockito会引用spring生成的bean,并对bean里的指定field进行重新注入。以达到实现部分mock功能 。
*/
@Test
public void injectClass() {
when(feeBusiness.getFee(anyLong())).thenReturn("spy inject");
assertEquals(injectProctBusiness.getCustomerName(1), "proctBusinessimpl->null");
assertEquals(injectProctBusiness.getCustomerPhone(2),"proctBusinessimpl->CustomerBusinessImpl->2");
assertEquals(injectProctBusiness.getOrderFee(3),"proctBusinessimpl->CustomerBusinessImpl->spy inject");
}
}