Mockito Verify: checked during check () than during invocation of bullying method

I call the performAction method with a list of objects and test it. After calling this method, I modify some of the "objects".

Mockito's error does not allow us to assert that the arguments do not match (showing changed objects), but I can see in debug mode that the objects were correct as needed.

Ideally, this should not happen, since validation should be applied based on when the method was actually called. Does the test check during call verification in the test method than during the call to the bullying method?

Testing class

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

Test Method:

 public void performActions(List<ABC> objects) { activity.doActivity(urlObjects2PerformAction); //Modify objects } 

The error I am getting is as follows (this is for the complete code. I gave the smallest possible snippet):

 Argument(s) are different! Wanted: activity.doActivity( ....... ...... 
+4
source share
2 answers

This was asked earlier - when Can Mockito check parameters based on their values ​​during a method call?

When you call a method that has been muffled by Mockito, Mockito will store the arguments that are passed to it, so you can use verify later. That is, it stores links to objects, not the contents of the objects themselves. If you subsequently change the contents of these objects, your verify call verify compare its arguments with the updated objects - it will not make a deep copy of the original objects.

If you need to check what the contents of objects are, you will need EITHER

  • store them yourself during a method call; OR
  • check them during method call.

The right way to do any of these is with the Mockito Answer . So, for the second option, you must create an Answer that performs the check and throws an AssertionFailedError if the argument values ​​are incorrect; instead of using verify at the end of the test.

+7
source

verify compares the contents of the parameter during the verify call, not when the bullying method is called. If the contents of the list are changed, then verify will use the changed values.

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

+1
source

Source: https://habr.com/ru/post/1498767/


All Articles