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;
}
utility.logToConsole(count);
}
}

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);
@Test
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

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a free website or blog at WordPress.com.

Up ↑

%d bloggers like this: