简体   繁体   English

单元测试事件监听器

[英]Unit Testing Event Listeners

I need to unit test the functionality of an event listener but I've never done it before and I can't seem to find an example anywhere about it. 我需要对事件监听器的功能进行单元测试,但我以前从未这样做过,而且我似乎无法在任何地方找到它的例子。 Does anyone have any suggestions on a good way to go about this? 有没有人有任何关于这个的好方法的建议?

There's not much to it, construct the event listener, pass in a mock event, and test. 它没有多少,构建事件监听器,传递模拟事件和测试。

@Test
public void testEventListener() {
  ActionListener subjectUnderTest = new MyActionListener();
  ActionEvent mockEvent = mock(ActionEvent.class);
  // Or just create a new ActionEvent, e.g. new ActionEvent();
  // setup mock

  subjectUnderTest.actionPerformed(mockEvent);

  // validate
}

Problems can arise when you follow the standard patterns for creating event listeners, where you define an anonymous class that directly interacts with the containing class. 当您按照标准模式创建事件侦听器时,可能会出现问题,您可以在其中定义直接与包含类交互的匿名类。 However it shouldn't be hard to refactor such a class into its own full class, and pass in any dependencies to the constructor, rather than implicitly from the surrounding class. 然而,将这样的类重构为它自己的完整类并将其传递给构造函数,而不是从周围的类隐式传递,应该不难。

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

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