mock主要目标之一是:屏蔽数据库操作。
必看:https://blog.csdn.net/flysun3344/article/details/52065492
Mockito官网: http://site.mockito.org/
示例
- 示例1
其中CommonService是目标测试类。CommonDao是CommonService中依赖的类。service内未嵌套其他service。
1、首先是引入CommonService,添加@Autowired和@InjectMocks注解。
2、引入CommonService依赖的CommonDao,添加@Mock注解。
public class CommonServiceTest extends BaseTest {
@Mock
private CommonDao commonDao;
@Autowired
@InjectMocks
private CommonService commonService;
@Test
public void queryBG() {
List<BusinessGroupVO> result = new ArrayList<>();
BusinessGroupVO vo = new BusinessGroupVO();
result.add(vo);
when(commonDao.queryBG(any(SuggestDTO.class))).thenReturn(result);
SuggestDTO dto = new SuggestDTO();
dto.setKeyword("北京");
dto.setLimit(10);
List<BusinessGroupVO> businessGroupVOS = commonService.queryBG(dto);
Assert.assertTrue("error", CollectionUtils.isNotEmpty(businessGroupVOS));
}
}
- 示例2
现在要写ServiceA的单测,ServiceA内嵌套了ServiceB。
首先重复上面的1和2两步。对于ServiceB的引用ServiceC,不需要引入。
然后,需要在ServiceA中添加ServiceB的set方法。否则实际执行的仍然是容器生成的service。可以通过debug查看service对象是容器生成的还是mock框架生成的。
返回值问题
注意,如果对有返回值的方法是用方式2模拟,当返回值类型不匹配(示例2中的返回值是string)时,会报错。
1.当mock一个对象,且执行此对象中的方法有返回值时,使用下面的方法:
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
对象= mock (类名.class);
when (对象.方法 (参数)).thenReturn (方法的返回值);
2.当mock一个对象,且执行此对象中的方法没有返回值时,使用下面的方法:
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
类名 对象 = Mockito.mock(类名.class);
Mockito.doAnswer(new Answer<Object>() {
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
return "called with arguments: " + args;
}
}).when(对象).方法名();