How to test an argument passed onto a method using ArgumentCaptor

--

Hi all!

Mockito has a list of uniquely useful components and ArgumentCaptor is one such example.

As the name suggests, ArgumentCaptor can be used to examine arguments passed onto methods, which cannot be accessed otherwise.

As usual, let’s dig into an example. Let’s assume we have a Util class as follows that simply prints whatever String argument is passed onto it.

public class Util {

public void shoutOut(String lifeQuote) {
System.out.println(lifeQuote);
}
}

Then let’s assume we have another class Dog that will be calling the Util’s method:

public class Dog {

private Util util;

public Dog(Util util) {
this.util = util;
}

public void bark() {
String lifeQuote = "I'm awesome";
this.util.shoutOut(lifeQuote);
}
}

In this kind of scenario, we wouldn’t have a way to test if the method shoutOut actually prints the desired life quote.

This is where ArgumentCaptor becomes useful as follows.

Some important points to notice:

  • The object Util needs to be mocked since the argument to be tested is passed onto a method in it
  • The ArgumentCaptor needs to be instantiated using the object type of the argument that is to be tested (In our case, “String”)
  • The verify method should be called on the mocked object

With the above in mind, we can write a test case as follows that will test the String value passed onto the shoutOut method.

Hope you learned something today.

Cheers!

--

--

Sachithra Dangalla
Sachithra Dangalla

No responses yet