Unit testing a Swing component

后端 未结 5 1748
清歌不尽
清歌不尽 2021-02-19 22:25

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

5条回答
  •  Happy的楠姐
    2021-02-19 22:49

    I've only been working with jMock for two days... so please excuse me if there is a more elegant solution. :)

    It seems like your FileTableModel depends on SwingUtilities... have you considered mocking the SwingUtilities that you use? One way that smells like a hack but would solve the problem would be to create an interface, say ISwingUtilities, and implement a dummy class MySwingUtilities that simply forwards to the real SwingUtilities. And then in your test case you can mock up the interface and return true for isEventDispatchThread.

    @Test
    public void testEventsNow() throws IOException {
        IFile testDir = mockDirectoryStructure();
    
        final ISwingUtilities swingUtils = context.mock( ISwingUtilities.class );
    
        final FileSystemEventsListener listener = 
                    context.mock(FileSystemEventsListener.class);
    
        context.checking(new Expectations()
        {{
            oneOf( swingUtils ).isEventDispatchThread();
                will( returnValue( true ) );
    
            oneOf(listener).currentDirectoryChanged(with(any(IFile.class)));
        }});
    
        FileTableModel model = new FileTableModel(testDir);
        model.setSwingUtilities( swingUtils ); // or use constructor injection if you prefer
        model.switchToInnerDirectory(1);
    }
    

提交回复
热议问题