Java 单元测试事件监听器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20977403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unit Testing Event Listeners
提问by endorphins
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?
我需要对事件侦听器的功能进行单元测试,但我以前从未做过,而且我似乎无法在任何地方找到有关它的示例。有没有人对解决这个问题的好方法有任何建议?
采纳答案by dimo414
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.
当您遵循创建事件侦听器的标准模式时,可能会出现问题,您可以在其中定义一个直接与包含类交互的匿名类。然而,将这样的类重构为它自己的完整类,并将任何依赖项传递给构造函数,而不是从周围的类隐式传递,应该不难。