【单元测试】Mockito常用场景示例
一、方法调用次数验证
public void test01() { Long channelProductionId = Long.MAX_VALUE; Date billDate = DateUtils.getDateOfDayBegin(new Date()); //模拟行为 Mockito.when(channelBillConfigService.getChannelBillConfigById(Long.MAX_VALUE)).thenReturn(newInstanceChannelBillConfig()); Mockito.when(channelBillHistoryService.getChannelBillHistory(Mockito.anyString(), Mockito.anyLong())).thenReturn(null); Mockito.doNothing().when(reportEventService).report(Mockito.any(ReportEvent.class)); billHistoryInitCommandExecutor.execute(channelProductionId, billDate); String yyyyMMdd = DateUtils.getDateTimeStr(new Date(), "yyyyMMdd"); Mockito.verify(channelBillHistoryService, Mockito.times(1)).getChannelBillHistory(yyyyMMdd + "origin.csv", Long.MAX_VALUE - 3); Mockito.verify(channelBillHistoryService, Mockito.times(1)).getChannelBillHistory("BCP" + yyyyMMdd + "Account.txt", Long.MAX_VALUE - 3); Mockito.verify(channelBillHistoryService, Mockito.times(2)).addChannelBillHistory(Mockito.any(ChannelBillHistory.class)); Mockito.verify(reportEventService, Mockito.times(1)).report(Mockito.any(ReportEvent.class)); }
二、方法调用入参信息验证
public void test01(){ Date date=new Date(); ChannelBillConfig channelBillConfig= newInstanceChannelBillConfigForDownloadTest(); channelBillConfig.setGetBillType(GetBillType.PULL_INTERFACE_HTTP); channelBillConfig.setProvideConfig("{\n" + "\t\"getBillType\": \"PULL_INTERFACE_HTTP\",\n" + "\t\"httpPullProviderConfigs\": [{\n" + "\t\t\"address\": \"www.baidu.com\",\n" + "\t\t\"fileNamesTpl\": \"HBcvs#yyyyMMdd#.txt,120#yyyyMMdd#origin.txt\",\n" + "\t\t\"protocol\": \"shCupDebit\",\n" + "\t\t\"data\": \"\"\n" + "\t}]\n" + "}"); ArgumentCaptor<BillCommand> argumentCaptor=ArgumentCaptor.forClass(BillCommand.class); Mockito.when(channelBillConfigService.getChannelBillConfigById(Long.MAX_VALUE)).thenReturn(channelBillConfig); Mockito.doNothing().when(billExecutorService).submit(Mockito.any(BillCommand.class)); billDownloadCommandExecutor.execute(Long.MAX_VALUE,date); Mockito.verify(billExecutorService,Mockito.times(1)).submit(argumentCaptor.capture()); HttpPullBillCommand httpPullBillCommand= (HttpPullBillCommand) argumentCaptor.getValue(); Assertions.assertTrue(httpPullBillCommand.getCurrentCommandEventType()== ReportEventType.BILL_HISTORY_DOWNLOAD); Assertions.assertTrue(httpPullBillCommand.getSftpInfo()[0].equals("sftp.meituan.sankuai.com")); Assertions.assertTrue(httpPullBillCommand.getSftpInfo()[1].equals("8080")); Assertions.assertTrue(httpPullBillCommand.createCurrentCommandLock().equals(Constants.BILL_LOCK_PREFIX + channelBillConfig.getId() + Constants.BILL_LOCK_PREFIX + DateUtils.getDateTimeStr(date, Constants.BILL_LOCK_DATE_FORMAT))); }