为什么我的 JFrame 没有出现在单元测试中?

Why does my JFrame not appear in Unit Test?

我正在尝试制作一个 JFreeChart 来比较已测试方法的问题大小与其 运行宁时间。

这里是制作散点图的class:

public class TestScatterPlot extends JFrame {
    public TestScatterPlot(String title, XYSeriesCollection dataset){
        super(title);
        JFreeChart chart = ChartFactory.createScatterPlot(
                "Time to problem size",
                "problem size",
                "time",
                dataset);
        XYPlot plot = (XYPlot)chart.getPlot();
        plot.setBackgroundPaint(new Color(255,228,196));


        // Create Panel
        ChartPanel panel = new ChartPanel(chart);
        setContentPane(panel);
    }
}

测试方法如下:

   @Test
   public void testHierholzersAlgorithm() {
        Map<Integer,Long> timeToProblemSize = new HashMap<>();
        for(int trial = 0;trial<1000;trial++) {
            //generate the test data
            long startTime = System.nanoTime();
            //run the method
            long runTime = System.nanoTime() - startTime;
            int dataSize = dataSize();
            //test the data
            timeToProblemSize.put(dataSize,runTime);


        }
        XYSeriesCollection dataset = new XYSeriesCollection();
        XYSeries series = new XYSeries("TimeToProblemSize");
        for(Integer probSize:timeToProblemSize.keySet()){
            series.add(probSize,timeToProblemSize.get(probSize));
        }
        dataset.addSeries(series);
        SwingUtilities.invokeLater(() -> {
            TestScatterPlot example = new TestScatterPlot("",dataset);
            example.setSize(800, 400);
            example.setLocationRelativeTo(null);
            example.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            example.setVisible(true);
        });
    }

当我运行这个时,图表框似乎开始出现然后立即关闭。

如何显示我的图表?

注:

这不是 this question 的重复,因为提问者正在使用扫描仪读取用户输入。此测试方法中没有扫描仪;所有输入都是随机生成的。

这也不是 this question 的重复。那里的提问者发生了 Thread.sleep。这里没有Thread.sleep。

我假设您正在 运行 将此作为单元测试,测试环境会在测试方法结束时立即停止测试。 invokeLater 此时可能还没有 运行。

您可以通过一个简单的测试来测试它,例如:

void test()
    {
        SwingUtilities.invokeLater(() -> {
            try
            {
                Thread.sleep(1000);
            }
            catch (InterruptedException e)
            {
                System.out.println("interrupt");
            }
            System.out.println("went through");
        });
    }

这将完全不执行任何操作,因为线程在它可以打印经过的过程之前被关闭。