Spy
Spy is a variation of a mock/stub, but instead of only setting expectations, spy records the calls made to the collaborator. The following example explains this concept:
class ResourceAdapter{ void print(String userId, String document, Object settings) { if(securityService.canAccess("lanPrinter1", userId)) { printer.print(document, settings); } } }
To test the print
behavior of the ResourceAdapter
class, we need to know whether the printer.print()
method gets invoked when a user has permissions. Here, the printer
collaborator doesn't do anything; it is just used to verify the ResourceAdapter
behavior.
Now, consider the following code:
class SpyPrinter implements Printer{
private int noOfTimescalled = 0;
@Override
public void print(Object document, Object settings) {
noOfTimescalled++;
}
public int getInvocationCount() {
return noOfTimescalled;
}
}
SpyPrinter
implements the Printer.print()
call, increments a noOfTimescalled
counter...