简体   繁体   中英

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;
}

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 (ie your listener) and do something with it later, it becomes challenging.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM