提问者:小点点

Mockito,如何验证上次调用方法的参数


在执行单元测试期间,该方法被调用了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());

    }

这一刻我得到了例外,因为发布事件方法没有被调用3次,而正是预期的BetSyncObj。它应该只在最后一次被调用。

因此,请告诉我如何检查上次是否使用预期的BetSyncObj对象调用了发布事件方法。


共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));