سؤال

I call a method performAction with list of objects and verify the same. After this method is called, I modify some of the "objects".

Mockito verify fails saying that arguments don't match (showing modified objects) but I can see in debug mode that objects were correct as needed.

Ideally, this should not happen as verify should be applied on the basis of when method was actually called. Does verify apply during verify call in test method than at the time of mocked method call?

Test Class

@Test
public void test() throws Exception {
    List<ABC> objects = new ArrayList<ABC>();
    //populate objects.
    activity.performActions(objects);               
    verify(activity, times(1)).doActivity(objects);
}

Method to test:

public void performActions(List<ABC> objects) {

    activity.doActivity(urlObjects2PerformAction);
    //Modify objects                

}

Error I am getting is as follows (this is for complete code. I have given smallest possible snippet):

Argument(s) are different! Wanted:
activity.doActivity(
.......
......
هل كانت مفيدة؟

المحلول

This has been asked before - at Can Mockito verify parameters based on their values at the time of method call?

When you call a method that has been stubbed with Mockito, Mockito will store the arguments that are passed to it, so that you can use verify later. That is, it stores object references, not the contents of the objects themselves. If you later change the contents of those objects, then your verify call will compare its arguments to the updated objects - it doesn't make a deep copy of the original objects.

If you need to verify what the contents of the objects were, you'll need to EITHER

  • store them yourself at the time of the method call; OR
  • verify them at the time of the method call.

The right way to do either of these is with a Mockito Answer. So, for the second option, you would create an Answer that does the verification, and throws an AssertionFailedError if the argument values are incorrect; instead of using verify at the end of the test.

نصائح أخرى

verify compares the parameter contents at the time verify is called and not when the mocked method is called. If the contents of the list is modified then verify will use the modified values.

An alternative is to use an Answer instead to check the parameters as soon as the method is called, or you can create a new list instead of modifying the old one.

this can be solved now using ArgumentCaptor

@Test
public void test() throws Exception {
    List<ABC> objects = new ArrayList<ABC>();
    ArgumentCaptor<List<ABC> objectsCaptor = ArgumentCaptor<List.class>;
    //populate objects.
    activity.performActions(objects);               
    verify(activity, times(1)).doActivity(objectsCaptor.capture());
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top