In Mockito we have a situation where the capture of a list doesn't return the expected result. Test case:
- We add "Pip" to a list
- We capture the list
- We add "Sok" to the list.
In our assert we only expect "Pip" to be there but "Sok" is there too. We think this is incorrect because at the time of capture "Sok" was not in the list.
java.lang.AssertionError:
Expected :[Pip]
Actual :[Pip, Sok]
- Has anyone got a solution for this?
- Is this a bug or a feature in Mockito?
- Why does Mockito keep a reference to the list and not make a copy of the list a capture time?
Here is the test case:
@RunWith(MockitoJUnitRunner.class)
public class CaptureTest {
@Captor
private ArgumentCaptor<List> listCapture;
@Mock
private ListPrinter listPrinter;
private TestClass testClass;
@Before
public void setUp() {
testClass = new TestClass(listPrinter);
}
@Test
public void testCapture() {
testClass.simulateFailSituation();
verify(listPrinter).printList(listCapture.capture());
// THIS FAILS: Expected:[Pip], Actual:[Pip, Sok]
assertEquals(Collections.singletonList("Pip"), listCapture.getValue());
}
public class TestClass {
private List list = new ArrayList();
private ListPrinter listPrinter;
public TestClass(ListPrinter listPrinter) {
this.listPrinter = listPrinter;
}
private void simulateFailSituation() {
list.add("Pip");
listPrinter.printList(list);
list.add("Sok");
}
}
public interface ListPrinter {
void printList(List list);
}
}