Using Mock for event listeners in unit-testing
- by phtrivier
I keep getting to test this kind of code (language irrelevant) :
public class Foo() {
public Foo(Dependency1 dep1) {
this.dep1 = dep1;
}
public void setUpListeners() {
this.dep1.addSomeEventListener(.... some listener code ...);
}
}
Typically, you want to test what when the dependency fires the event, the class under tests reacts appropriately (in some situation, the only purpose of such classes is to wire lots of other components, that can be independently tested.
So far, to test this, I always end up doing something like :
creating a 'stub' that implements both a addXXXXListener, that simply stores the callback, and a fireXXXX, that simply calls any registered listener. This is a bit tedious since you have to create the mock with the right interface, but that can do
use an introspective framework that can 'spy' on a method, and inject the real dependency in tests
Is there a cleaner way to do this kind of things ?