


Categories:
Software Design, Java, Testing
JMock and Multi Threading
I came across a problem recently regarding jMock and threading.
The problem was that the test seemed to have "passed", but the expectations set on the mock object were not executed.
The cause of this was because the test's thread was separate to the thread spawned by the program.
According to jMock - threading should be covered by integration testing, while jMock is meant to be used for unit testing - as such multi-threading is not supported.
However,there is a way around this...
Instead of spawning a thread in the program - create an interface which can be mocked. The implementation of the interface would have a method that accepted a Runnable class, and the thread would be spawned in this method.
The test would have it's own implementation of the interface, but instead of spawning a thread, the test would just execute the run() method of the Runnable class.
Here's a simple example:
public interface Runner {
void start(Runnable handle);
}
public class RunnerImpl implements Runner {
public void start(Runnable handle) {
Thread t = new Thread(handle);
t.start();
}
}
public class ThreadHandle implements Runnable {
public void run() {
//actual behaviour when the thread runs
}
}
public class Server {
private Runner runner;
private ThreadHandle handle;
public Server (Runner runner, ThreadHandle handle) {
this.runner = runner;
this.handle = handle;
}
public void startUp() {
//code...
runner.start(handle);
}
}
This would be the implementation class that the test would use:
public MockRunnerImpl implements Runner {
public void start(Runnable handle) {
handle.run(); //call run of the Runnable class instead of creating a thread and calling start()
}
}
Another way around this is to use Executor - this is described on jMock's site here
While I'm on the topic of jMock, another tip (applicable to 1.x versions) - when mocking concrete classes, use cglib. An example of this can be found here








Designing Faster Sites