HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaCritical

Can Mockito capture arguments of a method called multiple times?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
capturetimesmockitocalledmethodmultiplecanarguments

Problem

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 firstFooCaptor = ArgumentCaptor.forClass(Foo.class);
ArgumentCaptor secondFooCaptor = ArgumentCaptor.forClass(Foo.class);
verify(mockBar).doSomething(firstFooCaptor.capture());
verify(mockBar).doSomething(secondFooCaptor.capture());
// 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?

Solution

I think it should be

verify(mockBar, times(2)).doSomething(...)


Sample from mockito javadoc:

ArgumentCaptor peopleCaptor = ArgumentCaptor.forClass(Person.class);
verify(mock, times(2)).doSomething(peopleCaptor.capture());

List capturedPeople = peopleCaptor.getAllValues();
assertEquals("John", capturedPeople.get(0).getName());
assertEquals("Jane", capturedPeople.get(1).getName());

Code Snippets

verify(mockBar, times(2)).doSomething(...)
ArgumentCaptor<Person> peopleCaptor = ArgumentCaptor.forClass(Person.class);
verify(mock, times(2)).doSomething(peopleCaptor.capture());

List<Person> capturedPeople = peopleCaptor.getAllValues();
assertEquals("John", capturedPeople.get(0).getName());
assertEquals("Jane", capturedPeople.get(1).getName());

Context

Stack Overflow Q#5981605, score: 1057

Revisions (0)

No revisions yet.