unit testing, easymock
i wrote my first unit test that uses easymock today. easymock is a little tool that lets you easily create mock objects for your unit tests. mock objects are a kind of dummy implementation of the classes required by the class you are testing.
example: you have a class … ActionExecuter. that class takes objects that implement an Action interface and executes their execute() method.
public interface Action {
public void execute();
}
public class ActionExecuter {
public coid executeAction(Action action) {
action.execute();
}
}
you now want to test if this class really executes the execute method, so with easymock you write the following test:
public void ActionExecuterTest {
public void testExecuteAction() {
MockControl control = MockControl.createControl(Action.class);
Action action = (Action) control.getMock();
// record expected behavior
action.execute();
// indicate end of record phase
control.replay();
// run test
new ActionExecuter.executeAction(action);
// run easymock verification
control.verify();
}
}
so, you create that mock control and the mock object, which implements your Action interface. then you tell the mock object what method calls it should expect, and then you execute the class you want to test. the verify method verifies if the expectations were met.
of course you can do a lot more than this, but i hope this gives a rough idea. without easymock you’d have to implement you own Action implementation and write code to verify that the correct methods have been executed, and the correct paramaters have been passed. who’d wanna do that? ![]()
there is another project JMock, they specify the expected behaviour differently using string descriptions, check it out. don’t know what works better yet.
