barteks2x
barteks2x

Reputation: 1355

Verify that Collection argument from all method calls will together contain all values from given collection

I have a class to test that calls method from other class, that accepts a collection. I want to test, that all calls to this method together will contain all the values I expect, but the order and amount of calls is irrelevant.

I already implemented it without using mockito, but that anonymous class bothers me here:

@Test
public void test() {
    CubePos cubePos = new CubePos(0, 0, 0);

    Set<BlockPos> expected = new HashSet<>();
    BlockPos.getAllInBox(cubePos.getMinBlockPos(), cubePos.getMaxBlockPos()).forEach(expected::add);

    Set<BlockPos> actualPosSet = new HashSet<>();
    LightPropagator propagator = new LightPropagator() {
        @Override public void propagateLight(BlockPos centerPos, Iterable<BlockPos> coords, ILightBlockAccess blocks, EnumSkyBlock type,
                Consumer<BlockPos> setLightCallback) {
            coords.forEach(actualPosSet::add);
        }
    };

    FirstLightProcessor proc = makeProcessor(new TestLightBlockAccessImpl(20), propagator);
    proc.updateSkylightFor(cubePos);

    assertThat(actualPosSet, contains(expected));
}

(yes, the code is Minecraft-related, but the question isn't specific to that)

Upvotes: 0

Views: 278

Answers (1)

alayor
alayor

Reputation: 5035

You can use verify and ArgumentCaptor from mockito to check the arguments passed to propagator.propagateLight().

@Captor
private ArgumentCaptor<Iterable<BlockPos>> captor;

@Test
public void test() {
  ...
  LightPropagator propagator = mock(LightPropagator.class);
  FirstLightProcessor proc = makeProcessor(new TestLightBlockAccessImpl(20), propagator);
  proc.updateSkylightFor(cubePos);

  verify(propagator).propagateLight(any(), captor.capture(), any(), any(), any())
  Iterable<BlockPos> actualValues = 
      captor.getAllValues()
           .stream()
           .flatMap(i -> StreamSupport.stream(i.spliterator(), false))
           .collect(toList()); 
  assertThat(actualValues, containsInAnyOrder(expected.toArray(new BlockPos[0])));
}

Upvotes: 2

Related Questions