vendredi 27 février 2015

Mocking dependency that has setListener(...)



My class under test has a few dependencies. All of these provide setListener() as a way to receiving notification from their non-blocking operations.


I implemented a blocking method that aggregates the results from all the non-blocking ops. Which mean I have to register the listeners using such setListener() methods, and wait for the callbacks.


How should I mock/fake these dependencies in my unit test? I could subclass them and implement setListener() and fire the callbacks as necessary. But let's say some of these deps are final class. Also, I think there might be something I could use from Mockito?


Conceptual code (untested):



public void blockingMethod() {
CountDownLatch signal = new CountDownLatch(2);

dep1.setListener(new Dep1Listener() {
@Override public onResult(int result) {
signal.countDown();
}
});
dep1.calculateValue1();

dep2.setListener(new Dep2Listener() {
@Override public onResult(int result) {
signal.countDown();
}
});
dep2.calculateValue2();

signal.await();
return combinedResult;
}



Aucun commentaire:

Enregistrer un commentaire