nit testing individual classes is almost always useless. You need to unit test contracts or well-defined APIs instead. Why? Because testing and simulating APIs enables you to refactor a whole component with very few changes to the test. You can even rewrite the entire component without the tests knowing, since the tests depend only on the APIs they use and the APIs they simulate. They don't depend on any implementation classes.
This article introduces MockLib, a tool that simulates entire APIs (not just one single interface) using a mock library. It enables you to perform this more effective type of unit test. (If you have not read my first DevX article on Verifydesign, then you should read that first. Verifydesign helps you establish well-defined APIs.) Once you have cleaned up your projects so that implementations depend only on APIs, you are ready to start adding tests.
MockLib is a new open-source mocking library for Java, GWT, and C#. MockLib takes a completely different approach than other mock libraries. It simply acts as one big cache for the following:
- Parameters passed into a method
- Values returned from method calls made during the test
- Exceptions to be thrown when a method is called
- Code snippets that will be run when a method is called
- How each method was called (i.e., Stacktrace)
- The order in which the methods were called
Due to MockLib's caching nature, there is absolutely no need to "set up" a MockObject beforehand unless you know you will need to call methods and you will need to return values (or throw exceptions).
Unlike other mock libraries, the MockLib API contains only six classes! This is a huge advantage, as you have much less to learn than with other mock libraries. One of my favorite features is its ability to testin just nanosecondsa TimerTask scheduled to go off in 24 hours. I haven't seen another mock library that can do that yet. Nor have I found one that will help easily simulate an API like the ones in the forthcoming exampleswhen you need to simulate events back into the system you're testing.
The rest of this article shows how to use JMockLib to:
- Mock listeners
- Test listener implementations
- Test timer-triggered events
- Simulate an entire API instead of just one object
The differences between mock listeners and test listeners will be explained later in this article.