Java – get the number of simulated calls

Suppose I want to test such code:

class ClassToTest
  // UsedClass1 contains a method UsedClass2 thisMethod() {}
  UsedClass1 foo;
  void aMethod()
  {
    int max = new Random().nextInt(100);
    for(i = 0; i < max; i++)
    {
      foo.thisMethod().thatMethod();
    }
  }
}

If I have such a test:

ClassToTest test;
UsedClass1 uc1;
UsedClass2 uc2;
@Test
public void thingTotest() {
  test = new ClassTotest();
  uc1 = mock(UsedClass1.class);
  uc2 = mock(UsedClass2.class);
  when(uc1.thisMethod()).thenReturn(uc2);
  when(uc2.thatMethod()).thenReturn(true);

  test.aMethod();

  // I would like to do this
  verifyEquals(callsTo(uc1.thisMethod()),callsTo(uc2.thatMethod()));
}

How do I get to uc1 Thismethod() and UC2 The number of calls to thatmethod() so that I can check that they are called the same number of times?

Solution

You can use a custom verificationmode to calculate the number of calls. You can:

public class InvocationCounter {

    public static <T> T countInvocations(T mock,AtomicInteger count) {
        return Mockito.verify(mock,new Counter(count));
    }

    private InvocationCounter(){}

    private static class Counter implements VerificationInOrderMode,VerificationMode {
        private final AtomicInteger count;

        private Counter(AtomicInteger count) {
            this.count = count;
        }

        public void verify(VerificationData data) {
            count.set(data.getAllInvocations().size());
        }

        public void verifyInOrder(VerificationDataInOrder data) {
            count.set(data.getAllInvocations().size());
        }

        @Override
        public VerificationMode description(String description) {
            return VerificationModeFactory.description(this,description);
        }

    }

}

Then use it like this (also for void return types):

@Mock
private Function<String,Integer> callable;

AtomicInteger count= new AtomicInteger(); //here is the actual invocation count stored

countInvocations(callable,count).apply( anyString());

assertThat(count.get(),is(2));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>