One of the benefits to interaction-based unit testing is how much easier it is to truly test only the class under test and not its underlying implementation. You simply compose the class with all of the “worker” objects it needs to get its job done, and then mock them out in your test. Set your expectations of these mocked out objects and there you go; you are only testing your class’s implementation.
There is a complication in several of today’s most popular programming languages, however. The most popular mock generating libraries in C# and Java only provide full functionality for interfaces. No interface, no mock. No problem you say “As I am a good developer, I always design by contract and so all of my classes provide an interface.” Good for you, but what about File(C# and Java)? Or Point(.Net graphics)? Or any class from a less-enlightened third party library?
The answer is to wrap all such classes with an interface and a simple redirecting implementation, and then use that interface in your code instead of the real thing. Now you have the interface you need to mock out the class’s functionality. Consider replacing the code segment below:
With this instead:
Of course, you also must supply the interface and the implementation of the reflection class:
While this does represent a little extra work, it provides the very tangible benefit of making the MyBetterClass class much easier to test. Try this little tip while exploring interaction based testing and let me know what you think.
Interaction-based testing links:
Mocks Aren’t Stubs by Martin Fowler
State vs Interaction based Testing by Nat Pryce