[英]Why does my JFrame not appear in Unit Test?
我正在尝试制作一个 JFreeChart 来将测试方法的问题大小与其运行时间进行比较。
这是制作散点图的类:
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);
});
}
当我运行它时,图表框架似乎开始出现然后立即关闭。
如何让我的图表显示?
笔记:
这不是这个问题的重复,因为提问者正在使用扫描仪读取用户输入。 此测试方法中没有扫描仪; 所有输入都是随机生成的。
也不是重复这个问题。 那里的提问者发生了 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");
});
}
当线程在它可以打印通过之前关闭时,它什么也不做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.