首页 > 解决方案 > Mockito.when() 内的两次 ArgumentCaptor.capture()

问题描述

问题是我有两个argumentCaptors,我需要使用Mockito.when().then()两次,这个argumentCaptors.capture()在方法的参数里面when()。但它每秒运行两次argumentCaptor.capture()

我知道在验证中我可以使用argumentCaptor.getAllValues().get(i),并获取当前参数Captors的任何值,但我找不到关于如何在capture()方法中使用相同的东西的东西,里面Mockito.when()

Set<String> ordersBuy = mock(Set.class);
Set<String> ordersSell = mock(Set.class);

ArgumentCaptor<Function<CurrencyPairDTO, String >> getBase = ArgumentCaptor.forClass(Function.class);
ArgumentCaptor<Function<CurrencyPairDTO, String>> getCounter = ArgumentCaptor.forClass(Function.class);
ArgumentCaptor<Function<MyOrdersSmartDTO, Set<String>>> getSell = ArgumentCaptor.forClass(Function.class);
ArgumentCaptor<Function<MyOrdersSmartDTO, Set<String>>> getBuy = ArgumentCaptor.forClass(Function.class);

when(this.recalculateInMemoryBoardUtils.fillSetByMarginOrdersUsingFunctions(eq(instancesByUsername), eq(currencyBase), getBase.capture(), getSell.capture())).thenReturn(ordersSell);
when(this.recalculateInMemoryBoardUtils.fillSetByMarginOrdersUsingFunctions(eq(instancesByUsername), eq(currencyBase), getCounter.capture(), getBuy.capture())).thenReturn(ordersBuy);

我收到了两次 ordersBuy 而不是 ordersSell,ordersBuy

标签: javaspringtestingjunit

解决方案


我们可以在这里使用thenAnswer(),并检查我们的参数

when(this.recalculateInMemoryBoardUtils.fillSetByMarginOrdersUsingFunctions(eq(instancesByUsername), eq(currencyBase), any(), any())).thenAnswer( (Answer<Set<String>>) invocationOnMock -> { Function<CurrencyPairDTO, String> function = invocationOnMock.getArgument(2); CurrencyPairDTO currencyPairFunction = CurrencyPairDTO.builder() .base(currencyBase) .counter(currencyCounter) .build(); String currency = function.apply(currencyPairFunction); if (currencyBase.equals(currency)) { return ordersBuy; } else { return ordersSell; } });


推荐阅读