JUnit Argument Captor — enhance your mock testing

When writing mock tests it is, sometimes, more convenient to assert the values with which the methods were called using the ArgumentCaptor
class instead of the more usual mockĀ verify.
Let’s see both in action.

We’ll take as sample a mock of the List interface.

Let’s see how verify-ing would work:

Or since we expect those to be called in that same exact order we could also:

Now let’s use ArgumentCaptor instead:

That seems more streamlined and readable IMO. As you can see the ArgumentCaptor will catch all arguments with which it was called.

If you expect a single value to be captured or if you’re only interested in the last value with which your method was called you can also call:

In our case that call will return “three”.

Leave a Reply

Your email address will not be published. Required fields are marked *