Mockito really helps when you want to make white box testing. In addition to testing the results of some code, you can make sure that the code makes necessary method calls during its execution.
For example, the following method prints the current time:
public MyClass {
public void printTime(PrintStream ps) {
ps.print("Current time is: ");
Date now=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("hh:mm");
ps.print(sdf.format(now));
}
}Let's try to test this code. We want to make sure the code calls PrintStream 2 times, ignore the first call and check that the second one is in correct format: two digits, colon(:) and another two digits.
I started with writing a custom ArgumentMatcher just to check there is a semicolon in a string: