单元测试事件监听器 [英] Unit Testing Event Listeners

查看:139
本文介绍了单元测试事件监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要对事件侦听器的功能进行单元测试,但是我以前从未做过它,而且似乎找不到关于它的任何示例.有人对解决这个问题有任何建议吗?

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.

这篇关于单元测试事件监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆