简体   繁体   English

具有setListener(...)的模拟依赖项

[英]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. 所有这些都提供setListener()作为从其非阻塞操作接收通知的一种方式。

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. 这意味着我必须使用此类setListener()方法注册侦听器,然后等待回调。

How should I mock/fake these dependencies in my unit test? 如何在单元测试中模拟/伪造这些依赖项? I could subclass them and implement setListener() and fire the callbacks as necessary. 我可以将它们子类化并实现setListener()并根据需要触发回调。 But let's say some of these deps are final class. 但是,可以说其中一些部门是final堂课。 Also, I think there might be something I could use from Mockito? 另外,我认为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. 一旦模拟需要保留一个参数(即您的听众)并在以后对其进行处理,就变得很有挑战性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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