Using Mock for event listeners in unit-testing

Posted by phtrivier on Programmers See other posts from Programmers or by phtrivier
Published on 2012-10-10T17:30:27Z Indexed on 2012/10/24 5:26 UTC
Read the original article Hit count: 298

Filed under:

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 ?

© Programmers or respective owner

Related posts about unit-testing