I had this very issue today, and I didn't want to use PowerMock or other stuff. I just wanted to make a test that made sure a certain method was called. I found this post and I saw that nobody had mentioned this approach.
One way of achieving this without adding in more dependencies or similar is pretty low tech, but it works:
@Test
public void testSomeMethodIsCalledOnce() throws Exception {
final AtomicInteger counter = new AtomicInteger(0);
Mockito.when(someObject.theMethodIWant(anyString()))
.then((Answer<ReturnValue>) __ -> {
teller.incrementAndGet();
return theExpectedAnswer;
});
theObjectUnderTest.theMethod(someTestValue);
assertEquals(1, teller.get());
}
This is pretty simple, and it's easy to see what's going on. When the method I want is called (it's mocked here), do this stuff. Amongst the stuff is a call to incrementAndGet for the AtomicInteger. You could use an int[] here, but that's not as clear in my opinion. We're just using something that's final, which we can increment. That's a limitation of the lambda we're using.
It's a bit crude, but it gets the job done in a simple and straightforward matter. At least if you know your lambdas and Mockito.