I’ve been using EasyMock with my unit tests on a current project. Generally, it’s been useful; to configure my project to run in a test environment on my desktop is a really pain. By using EasyMock I can create a very controlled environment for my tests by faking just enough of it to run.
The documentation is fairly small, here is a link.
Briefly, you create a MockControl object from the base class:
MockControl myPencil = MockControl.createControl(Writer.class);
Caveat- The mocked class must implement an interface.
Next, you can get a mock implementation of the interface:
Writer mockPencil = (Writer)myPencil.getMock();
Now, with the mock and mockcontrol in hand, you can tell it how you want it to perform.
mockPencil.write("Something to write");
myPencil.setReturnType(new OutputStream());
mockPencil.erase("Something to erase");
myPencil.setVoidCallable();
And when you’re done, always call:
myPencil.replay();
Run your test, and your mock object will take the place of the real thing.
A couple other notes:
- You can specify any return type, including throwables
- You must specify the number of times you expect a method to be called, the mock will throw an exception if it receives something other than what you specify
Finally, sometimes the exceptions can be difficult to interpret. Take this recent stacktrace I received as an example:
junit.framework.AssertionFailedError:
Unexpected method call lockHistory(Context: user=IOP-10.25.2006.05.05,workflowId=null, ( id = 00000010 (00000010) )):
lockHistory(Context: user=IOP-10.25.2006.05.05,workflowId=null, ( id = 00000010 (00000010) )): expected: 0, actual: 1
lockHistory(Context: user=IOP-10.25.2006.05.05,workflowId=null, ( graphUuid = 00000010 (00000010) )): expected: 1, actual: 0
at org.easymock.MockControl$4.invoke(MockControl.java:148)
at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:44)
at $Proxy0.lockHistory(Unknown Source)
It’s telling me that it expected to receive a call to lockHistory with user=IOP-10.25.2006.05.05, workflowId=null, ( id = 00000010 (00000010) ). But instead it received… uh… the … same … thing?
Normally the exception provides different values and it’s not as tricky to track down the cause of the difference. I normally debug through the code as the test runs to find and fix the problem. I’ll let you know what I find in this case.
One Comment
It turned out this this unexpected call to lockHistory was being called in a finally section of a try/catch, after an exception was thrown and swallowed.
Post a Comment