Can Mockito capture arguments of a method called multiple times? [java]


If you don't want to validate all the calls to doSomething(), only the last one, you can just use ArgumentCaptor.getValue(). According to the Mockito javadoc:

If the method was called multiple times then it returns the latest captured value

So this would work (assumes Foo has a method getName()):

ArgumentCaptor<Foo> fooCaptor = ArgumentCaptor.forClass(Foo.class);
verify(mockBar, times(2)).doSomething(fooCaptor.capture());
//getValue() contains value set in second call to doSomething()
assertEquals("2nd one", fooCaptor.getValue().getName());


I have a method that gets called twice, and I want to capture the argument of the second method call.

Here's what I've tried:

ArgumentCaptor<Foo> firstFooCaptor = ArgumentCaptor.forClass(Foo.class);
ArgumentCaptor<Foo> secondFooCaptor = ArgumentCaptor.forClass(Foo.class);
// then do some assertions on secondFooCaptor.getValue()

But I get a TooManyActualInvocations Exception, as Mockito thinks that doSomething should only be called once.

How can I verify the argument of the second call of doSomething?

How to verify a method is called two times with mockito verify()

Using the appropriate VerificationMode, of course:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

verify(mockObject, atLeast(2)).someMethod("was called at least twice");
verify(mockObject, times(3)).someMethod("was called exactly three times");

In my original comment, this was the answer I had in mind.

The class to be mocked:

class MockedClass{
    void save(SomeBean sb){

The class we'll need to verify the Date object is null.

class SomeBean{
    Date date;

    Date getDate(){return date;}

    void setDate(Date date){;}

The class under test:

class TestClass{
    MockedClass mc;

    TestClass(MockedClass mc){ = mc;}

    void doWork(){
        SomeBean sb = new SomeBean();;
        sb.setDate(new Date());;

And the test case:

public void testAnswer(){
    MockedClass mc = Mockito.mock(MockedClass.class);
    Mockito.doAnswer(new Answer<Void>(){
        boolean checkDate = true;
        public Void answer(InvocationOnMock invocation) throws Throwable {
            SomeBean sb = (SomeBean) invocation.getArguments()[0];
            if(checkDate && sb.getDate() != null){
                throw new NullPointerException(); //Or a more meaningful exception
            checkDate = false;
            return null;

    TestClass tc =  new TestClass(mc);

The first time through this Answer (The term I should have used in my original comment), this will throw an exception and fail the test case if date is not null. The second time through, checkDate will be false, so the check will not be performed.