views:

32

answers:

1

Hello, I'm having a problem with ArgumentCaptor not being able to record the arguments when calling the same method a number of times. Basically this does not seem to work:

List<Dummy> mList = mock(List.class);
Dummy dummy = new Dummy();
when(mList.get(anyInt())).thenReturn(dummy);

Dummy d = mList.get(12);
d.setName("John");
mList.add(d);

Dummy g = mList.get(10);
g.setName("Ben");
mList.add(g);
...

verify(mymock, times(3)).doStuff(captor.capture)); 
assertEquals("John", captor.getAllValues().get(0).getName()); 
assertEquals("Ben", captor.getAllValues().get(1).getName()); 
assertEquals("Don", captor.getAllValues().get(2).getName()); 

The value of getName() is always set to "Don". I have also tried using InOrder, with the same outcome.

Feature (and me stupiud) or bug?

To better explain the issue I have created a use case: http://pastebin.com/RE1UzJ4F

Cheers

A: 

The java doc for ArgumentCaptor suggests what you are trying, so I'd say this is a bug. However, it is a bug in your code.

The problem is that you're changing the name of the same dummy each time you're invoking setName(..). I'd suggest that you make Dummy immutable and avoid setters wherever you can. That will avoid these types of bugs.

iwein
Yes, of course, the test code was just a way to explain the problem.
Luciano Fiandesio
My point is that the only problem is in fact in your code, not in Mockito. Is that what you were trying to explain (in that case I'm sorry I missed it)?
iwein
I've fixed your sample in the pastebin (without compiling though).
iwein