on Jul 11th, 2009Testing hard to test code with EasyMock
If you are into unit testing, you may find EasyMock quite useful. It is very valuable for making hard-to-test-code testable.
For example I recently was adding tab-switching via keyboard to Riena. The state of each tab is kept in an interface named INavigationNode which has about 40 methods (!). Creating a mock by hand for such a big interface would not be fun at all. With EasyMock it just takes is a call to:
ISubApplicationNode nodeA = EasyMock.createMock(ISubApplicationNode.class);
The code for determining the next tab, depends strictly on the isSelected property. Manipulating the return value of this method takes just another EasyMock call:
EasyMock.expect(nodeA.isSelected()).andReturn(true);
This tells EasyMock that nodeA.isSelected() will be called once and should return true.
After everything is set-up I switch from ‘record’ to ‘play-back’ mode:
EasyMock.replay(nodeA);
Here’s a full example of a test case:
protected void setUp() throws Exception { super.setUp(); handler = new SwitchSubApplication(); nodeA = EasyMock.createMock(ISubApplicationNode.class); nodeB = EasyMock.createMock(ISubApplicationNode.class); nodeC = EasyMock.createMock(ISubApplicationNode.class); } public void testFindNextSubApplicationAtoB() { EasyMock.expect(nodeA.isSelected()).andReturn(true); EasyMock.replay(nodeA); ISubApplicationNode[] nodes = { nodeA, nodeB, nodeC }; assertSame(nodeB, handler.findNextNode(nodes)); }
This post barely scratches the surface. Curious? Read this nice EasyMock introduction.
Image: (c) *Micky/flickr. Licensed under creative commons.
Related posts:


If you tried EasyMock and you find it useful, then try Mockito too. I’ve been using both libraries and find Mockito a little bit more developer friendly (in term of writing code). Project is availible at mockito.org (http://code.google.com/p/mockito/).
I’m starting to use EasyMock; it’s pretty nice, if a little messy. The classextension package has some really nice behavior.
Love EasyMock. It is absolutely great.
Something that I would recommend is the use of the IMockControl object. Using the IMockControl, you code can change from this:
EasyMock.replay(nodeA);
EasyMock.replay(nodeB);
EasyMock.replay(nodeC);
// execute logic….
EasyMock.verify(nodeA);
EasyMock.verify(nodeB)
EasyMock.verify(nodeC)
To this:
setup() {
mockControl = EasyMock.createControl();
nodeA = mockControl.createMock(ISubApplicationNode.class);
nodeB = mockControl.createMock(ISubApplicationNode.class);
nodeC = mockControl.createMock(ISubApplicationNode.class);
}
testX() {
expect(nodeA).andReturn();
expect(nodeB).andReturn();
…
mockControl.replay();
// execute logic
mockControl.verify();
}
Found this niceness by asking questions on the mailing list….
Enjoy…