Thursday, November 6, 2003

EasyMock

EasyMock is a library to help create mock objects that aid in your unit testing. The framework uses dynamic proxies to implement a given interface and return the results you expect. It will also throw exceptions if an unexpected method is called (aiding in the creation of your mock objects) and count the number of times a method is called (which allows your unit test to test efficiency in a more measurable way than the usually pointless System.currentTimeMillis() method of testing).

The best advantage of using EasyMock, in my opinion, is to specify the results of your mock objects directly in your unit test. A simple test may call two or three methods on a class. EasyMock requires two lines to create the mock object:

MockControl control = MockControl.createControl(MyInterface.class);
MyInterface myMockObj = MockControl.getMock();

Each method you want to call needs to have its results defined:

myMockObj.getParm();
control.setReturnValue(�ABC�);

As you can see, setting up a simple method call requires only two lines of code. This allows you to create custom mock objects for different situations you may want to test without littering your source tree with mock objects (or filling your mock objects with logic that, itself, needs to be tested).

The limitation of EasyMock, of course is the dependency on interfaces. Although we should always be coding to interfaces, it rarely seems to work that way. Luckily, most need for Mock Objects will be limited to those classes that do (or should) have well defined interfaces (database access, file access, container classes such as doms, or classes with complicated logic).

Labels:

0 Comments:

Post a Comment



<< Home