在执行单元测试期间,该方法被调用3次。每次使用不同的参数调用它。我想验证,最后一次使用相应的参数调用方法。
请帮助我。
我的方法:
private void doHandle(Updategram updategram)
throws FixtureNotFoundException, DatatypeConfigurationException {
BetSyncObject betSyncObject = transformer.transformer(updategram);
EventTreeCreation event = betSyncObject.eventTree;
if (!event.getEvent().isEmpty()) {
Event event2 = event.getEvent().get(0);
long timestamp =
updategram.getHeader().getTimeStampUtc().toGregorianCalendar().getTimeInMillis();
String sportName = event2.getSportcode();
String id = event2.getExtId();
publisher.publishEvent(PROVIDER_NAME, betSyncObject, sportName, id, timestamp);
} else {
LOGGER.info("Empty event tree : {}", betSyncObject);
}
}
测试:
@Test
public void testCountAndSetResultLine() throws Exception{
EventPublisher eventPublisher = Mockito.mock(EventPublisher.class);
BetgeniusService betgeniusService = new BetgeniusService();
BetSyncObject expectedBetSyncObj = transformer.transformer(updategram);
ExecutorService service = Executors.newFixedThreadPool(3);
handle(betgeniusService, updategramFixture, service);
Thread.sleep(50);
handle(betgeniusService, updategramMarketSet, service);
Thread.sleep(50);
handle(betgeniusService, updategramResult, service);
service.shutdown();
service.awaitTermination(20000, TimeUnit.MILLISECONDS);
betgeniusService.getExecutor().shutdown();
betgeniusService.getExecutor().awaitTermination(20000, TimeUnit.MILLISECONDS);
Mockito.verify(eventPublisher, Mockito.times(3)).publishEvent(Mockito.anyString(), Mockito.any(BetSyncObject.class),
Mockito.anyString(), Mockito.anyString(), Mockito.anyLong());
}
目前我正在获得异常,因为publishEvent
方法未被调用3次,而expectedBetSyncObj
正好被调用。应该只在最后一次调用它。
那么,请告诉我如何检查最后一次使用publishEvent
对象调用expectedBetSyncObj
方法。
答案 0 :(得分:1)
我认为你可以通过ArgumentCaptor实现这一目标。
使用ArgumentCaptor获取所有调用的参数,然后验证它们中的每一个。
在您的情况下,您将验证在第三次调用时,参数(.get(2)
)是预期的对象。
类似
ArgumentCaptor<BetSyncObject> betSyncObjectCaptor = ArgumentCaptor.forClass(BetSyncObject.class);
Mockito.verify(eventPublisher, Mockito.times(3)).publishEvent(Mockito.anyString(), betSyncObjectCaptor.capture(), Mockito.anyString(), Mockito.anyString(), Mockito.anyLong());
List<BetSyncObject> capturedBetSyncObject = betSyncObjectCaptor.getAllValues();
assertEquals(expectedBetSyncObj, capturedBetSyncObject.get(2));