单元测试Swing组件 [英] Unit testing a Swing component

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

问题描述

我正在编写类似TotalCommander的应用程序。我有一个单独的文件列表组件,以及它的模型。模型支持侦听器并以下列方式发出 CurrentDirChanged 等事件的通知:

I am writing a TotalCommander-like application. I have a separate component for file list, and a model for it. Model support listeners and issues a notification for events like CurrentDirChanged etc. in following manner:


private void fireCurrentDirectoryChanged(final IFile dir) {
    if (SwingUtilities.isEventDispatchThread())
        for (FileTableEventsListener listener : tableListeners)
            listener.currentDirectoryChanged(dir);
    else {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                for (FileTableEventsListener listener : tableListeners)
                    listener.currentDirectoryChanged(dir);
            }
        });
    }
}

我为此写了一个简单的测试:

I've written a simple test for this:


@Test
public void testEvents() throws IOException {
    IFile testDir = mockDirectoryStructure();
    final FileSystemEventsListener listener = 
                context.mock(FileSystemEventsListener.class);
    context.checking(new Expectations() {{
        oneOf(listener).currentDirectoryChanged(with(any(IFile.class)));
    }});

    FileTableModel model = new FileTableModel(testDir);
    model.switchToInnerDirectory(1);
}

这不起作用,因为没有 EventDispatchThread 。有没有办法在无头构建中进行单元测试?

This does not work, because there is no EventDispatchThread. Is there any way to unit test this inside the headless build?

单元测试java swing jmock

unit-testing java swing jmock

推荐答案

注意,一般来说在UI上进行单元测试总是很困难,因为你必须模拟出很多不可用的东西。

因此,开发应用程序(任何类型)的主要目的始终是尝试分离UI来自主应用程序逻辑的东西尽可能多。在这里拥有强大的依赖性,使单元测试真的很难,基本上是一场噩梦。这通常通过使用 MVC 一种方法,主要测试控制器类,而视图类除了构建UI并将其操作和事件委派给控制器之外什么都不做。这分离了责任并使测试更容易。

Note, generally speaking unit testing on UI stuff is always difficult because you have to mock out a lot of stuff which is just not available.
Therefore the main aim when developing applications (of any type) is always to try to separate UI stuff from the main application logic as much as possible. Having strong dependencies here, make unit testing really hard, a nightmare basically. This is usually leveraged by using patterns like a MVC kind of approach, where you mainly test your controller classes and your view classes do nothing than constructing the UI and delegating their actions and events to the controllers. This separates responsibilities and makes testing easier.

此外,您不一定要测试框架提供的内容,例如测试事件是否被正确触发。你应该自己测试你正在编写的逻辑。

Moreover you shouldn't necessarily test things which are provided by the framework already such as testing whether events are correctly fired. You should just test the logic you're writing by yourself.

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

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