2、前期准备org.jmockit jmockit 1.30 test junit junit 4.11 test
public class AppVersionTest {
@Tested
AppVersionService appVersionService;
@Injectable
AppVersionEntityMapper appVersionEntityMapper;
@Injectable
private RedisService redisService;
@BeforeAll
public static void before(){
}
public void init(){
ReflectionTestUtils.setField(appVersionService, "host", "http://wwww.costco.com.cn");
ReflectionTestUtils.setField(appVersionService, "iosUrl", "http://wwww.apple.com.cn");
}
}
@Tested: 需要被测试的类
@Injectable: 注入依赖
@BeforeAll: 在当前类的所有测试方法之前执行
init(): 为被测试的类中的特定属性注入值
public class AppVersionService {
@Autowired
private AppVersionEntityMapper appVersionEntityMapper;
@Autowired
private RedisService redisService;
@Value("${image.host}")
private String host;
@Value("${app.ios}")
private String iosUrl;
}
3、unit test
@Test
public void getLastAppVersionByDeviceTest() {
init();
new Expectations() {
{
redisService.hasKey(anyString);
result = true;
redisService.get(anyString, AppVersionDto.class);
AppVersionDto dto = new AppVersionDto();
dto.setDescription("测试用例desc");
result = dto;
}
};
AppVersionDto dto = appVersionService.getLastAppVersionByDevice("android", 3);
Assertions.assertEquals(dto.getDescription(), "测试用例desc");
录制函数行为
可以录制多个函数调用,result对应最近的调用函数的结果赋值。
new Expectations(){
{
}
}
验证
验证redisService.get() 是否调用了1次。
new Verifications() {
{
redisService.get(anyString, AppVersionDto.class);
times = 1;
}
};
4、特殊情况
1、被测试类中,有Example
// 被测试方法
public AutoEntity getAutoRenewalOrderDetail(String tradeNo){
Example example = new Example(AutoEntity.class);
example.createCriteria().andEqualTo("tradeNo", tradeNo);
return autoEntityMapper.selectOneByExample(example);
}
EntityHelper.initEntityNameMap(AutoEntity.class, new Config());
new Expectations(){
{
mapper.selectOneByExample(any);
result = req;
}
};
2、被测试类中调用了其他方法或静态方法
// getToken方法在DmHubService类中 new MockUp(DmHubService.class) { // 如果是静态方法,需将String 前的 static 关键字去掉 @Mock String getToken(String sendBody) { return "token"; } };
私有方法不能被 MockUp
3、多线程
// 被测试方法 public void asycCacheUnreadMsgCount(Listlist){ ExecutorService executorService = ThreadPoolUtils.getSingleExecutorService("asycCacheUnreadMsgCount"); try { executorService.execute(() -> { list.forEach(e -> messageService.cacheMemberUnreadMsgCount(e.getMemberId(), 1L)); }); }finally { executorService.shutdown(); } }
new MockUp(ThreadPoolUtils.class) { @Mock public ThreadPoolExecutor getSingleExecutorService(String poolName){ // MockUp 返回的线程 return new ThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS, new linkedBlockingQueue (10000) ,new ThreadFactoryBuilder().setNameFormat(poolName + "-pool-%d").build(), new ThreadPoolExecutor.CallerRunsPolicy()); } }; new MockUp () { @Mock public void execute(Runnable command) { // 执行线程 command.run(); } };



