An example : Unit test using Argument Captor

How do you write unit test for the argument of a method call inside the method which returns void?

Have a look at the code snippet below:

public class MainClass {
Utility utility;
public MainClass(Utility utility){
this.utility = utility;
* Counts the occurrences of given character ch
* in the given text
* @param text
* @param ch
public void countNumberCharacter(String text, char ch) {
char[] charArray = text.toCharArray();
int count = 0;
int i = 0;
while(i < charArray.length){
if(charArray[i] == ch)
count += 1;
i += 1;
view raw gistfile1.txt hosted with ❤ by GitHub

As mentioned in the comment, the method countNumberCharacter simply counts the number of occurrences of character ch in the given string text. The count is then logged to the console via a utility method called log to console.

What if you want to write the unit test for the count?

Fortunately, Mockito comes with a Class called ArgumentCaptor. Argument Captor provides an opportunity to capture argument values for assertion.

We need to first add dependency of Mockito before using the Arguement Captor.  Link to Mockito dependency.

Refer to the code snippet of junit test of the class shown above to see an example of Argument Captor at work.

public class MainClassTest {
Utility utility = mock(Utility.class);
public void testCountofCharacter(){
String testText = "Harvey : I don’t play the odds, I play the man.";
MainClass mainClass = new MainClass(utility);
mainClass.countNumberCharacter(testText, 'e');
ArgumentCaptor<Integer> actualCount = ArgumentCaptor.forClass(Integer.class);
verify(utility, times(1)).logToConsole(actualCount.capture());
//Expected Number of 'e' in test text.
//Harv'e'y : I don't play th'e' odds, I play th'e' man.
Assert.assertEquals(3, (long)actualCount.getValue());
view raw gistfile1.txt hosted with ❤ by GitHub


If you liked this article and would like one such blog to land in your inbox every week, consider subscribing to our newsletter:

Leave a Reply

Up ↑