I use an approach similar to Jon's, but instead of creating a specialized interface just for the current time (say, Clock
), I usually create a special testing interface (say, MockupFactory
). I put there all the methods that I need to test the code. For example, in one of my projects I have four methods there:
- one that returns a mock-up database client;
- one that creates a mock-up notifier object that notifies the code about changes in the database;
- one that creates a mock-up java.util.Timer that runs the tasks when I want it to;
- one that returns the current time.
The class being tested has a constructor that accepts this interface among other arguments. The one without this argument just creates a default instance of this interface that works "in real life". Both the interface and the constructor are package private, so the testing API doesn't leak outside of the package.
If I need more imitated objects, I just add a method to that interface and implement it in both testing and real implementations.
This way I design code suitable for testing in the first place without imposing too much on the code itself. In fact, the code becomes even cleaner this way since much factory code is gathered in one place. For example, if I need to switch to another database client implementation in real code, I only have to modify just one line instead of searching around for references to the constructor.
Of course, just as in the case with Jon's approach, it won't work with 3rd party code that you are unable or not allowed to modify.