gpt4 book ai didi

java - 如何创建支持重绘功能的 JFrame/JPanel 模拟

转载 作者:太空宇宙 更新时间:2023-11-04 11:59:20 26 4
gpt4 key购买 nike

我在 Swing 应用程序的单元测试中遇到了一些问题。我想要做的是将一个可绘制对象传递给我的 JPanel,每次我这样做时,它都应该重新绘制自己。

基本场景就这么多,现在开始我的单元测试:

public class GraphicViewImplTest {

private JFrame frame;
private GraphicViewImpl view; //This is my JPanel
private GraphicLineSpy firstGraphicLine;
private Line firstLine;

@Before
public void setUp() throws Exception {
frame = new JFrame();
view = new GraphicViewImpl();
frame.add(view);
frame.setVisible(true);
firstLine = new Line();
firstLine.setStart(new Point(11, 12));
firstLine.setEnd(new Point(21, 22));
firstGraphicLine = new GraphicLineSpy(firstLine);
}

@Test
public void whenReceivingLine_shouldPaintLine() {
view.receiveShape(firstGraphicLine);
assertTrue(firstGraphicLine.wasPainted());
}

}

如您所见,我正在将 GraphicLineSpy 传递到我的 View 。 GraphicLine 类基本上是 Line 类的装饰器,它知道如何在 Swing 中绘制线条。 GraphicLineSpy 重写了 GraphicLine 的 Paint 方法,只是将一个标志设置为 true,这样我就可以检查 Paint 方法是否被调用。

现在开始实现我的 GraphicView JPanel:

public class GraphicViewImpl extends JPanel implements GraphicView, Observer {

protected GraphicViewPresenter presenter;
protected List<GraphicShape> graphicShapeList = new LinkedList<>();

@Override
public void receiveShape(GraphicShape graphicShape) {
graphicShapeList.add(graphicShape);
graphicShape.addObserver(this);
repaint();
}

@Override
public void removeShape(GraphicShape graphicShape) {
graphicShapeList.remove(graphicShape);
graphicShape.removeObserver(this);
repaint();
}

public void setPresenter(GraphicViewPresenter presenter) {
this.presenter = presenter;
}

@Override
public void update() {
repaint();
}

@Override
public void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
for (GraphicShape graphicShape : graphicShapeList)
graphicShape.paint(graphics);
}
}

现在,我的问题是,当我运行这些测试时,他们说我的 GraphicLine 未绘制。然而,当我实际运行该程序并添加一个新的 GraphicLine 时,它​​工作得很好,我所有的形状都被绘制了。我在测试设置中遗漏了什么吗?

此外,这可能是最重要的部分,我想每次运行测试时启动整个 JFrame 并不是真正的最佳解决方案,所以我想知道如何最好地创建一个不会破坏整个重绘功能的测试替身。

预先感谢您的任何提示!

最佳答案

我认为您应该专注于测试您的代码而不是 JPanel 实现,因此您应该使用 Mockito 框架(或任何其他框架)模拟这些其他依赖项:

public class GraphicViewImplTest {

@Rule
public MockitoRule rule = MockitoJUnit.rule();
@Mock
private Graphics2D graphics; // not tested dependency
@Mock
private GraphicShape firstLine; // not tested dependency

private GraphicViewImpl view; //This is my JPanel

@Before
public void setUp() throws Exception {
view = spy(new GraphicViewImpl());
doNothing().when(view).repaint();
}

@Test
public void whenReceivingLine_shouldPaintLine() {
view.receiveShape(firstGraphicLine);
verify(view).repaint();
verify(firstLine,never()).paint(graphics);

view.paintComponent(graphics);
verify(firstLine).paint(graphics);
}
}

关于java - 如何创建支持重绘功能的 JFrame/JPanel 模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41077841/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com