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:

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.

 

Advertisements

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

Blog at WordPress.com.

Up ↑

%d bloggers like this: