Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito Verify: Verified during verify() than during mocked method call

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(
.......
......
like image 512
instanceOfObject Avatar asked Jan 12 '23 13:01

instanceOfObject


1 Answers

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.

like image 168
Dawood ibn Kareem Avatar answered Feb 08 '23 12:02

Dawood ibn Kareem