Testing 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.