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;
}
I would create concrete implementations of your dependencies that return fixed values. I wouldn't subclass existing classes, instead create minimal implementations of your interfaces. If you don't have interfaces defined for the dependencies, create them.
Mocking may work, but the tests would be harder to read. As soon as a mock needs to hold onto an argument (i.e. your listener) and do something with it later, it becomes challenging.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments