junit测试覆盖的油漆组件 [英] junit testing overridden paint component

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

问题描述

我在测试覆盖的油漆组件时遇到问题.

I am having problem testing my overridden paint components.

我删除了很多代码以简化操作

I have removed a lot the code to simplify things

 @Override
    protected void paintComponent(Graphics g) {
                g.setColor(Color.RED);
                int y = //some come;
                int height = //some code
                //for loop
                g.clearRect(1, y, getWidth(), height);
                g.drawRect(1, y, getWidth(), height);
            }
        }
        super.paintComponent(g);
    }

我的绘画组件创建了多个矩形.我需要获得有关绘制的矩形数量及其高度的详细信息.我不确定如何进行单元测试.

My paint component creates multiple rectangles. I need to get details on the number of rectangles drawn and their height. I'm not sure how to make a unit test to do this.

我尝试使用TextAreas的getComponents()方法,但是它返回null.我以为调用repaint()会触发paint组件执行.

I've tried to use the TextAreas' getComponents() method but it returns null. I thought calling repaint() would trigger the paint component to execute.

感谢您的帮助

推荐答案

我可以想到2种解决方案:

There are 2 solutions I can think of:

使用BufferedImage中的Graphics调用组件的paint方法.所以,

Call your component's paint method with the Graphics from a BufferedImage. So,

BufferedImage bi = new BufferedImage(width,height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = bi.createGraphics();
yourComponent.setSize(width,height);
yourComponent.paint(g2);
g2.dispose();

分析bi的内容.

选项2,您可以使组件暴露其绘制的内容.绘制矩形后,记录您的通话内容.然后从对象中使该对象可用.如果您需要特定尺寸,这可能会更有用.

Option 2, you can make your component expose what it has painted. As your rectangles are drawn, record what calls you make. Then make that available from the object. This may be more useful if you need specific dimensions.

private StringBuilder sb = new StringBuilder();
public String getOperations() {
    return sb.toString();
}
@Override
protected void paintComponent(Graphics g) {
    sb.setSize(0);
    g.setColor(Color.RED);
    sb.append("Color(red),");
    int y = //some come;
    int height = //some code
    //for loop
    g.clearRect(1, y, getWidth(), height);
    sb.append("Clear(").append(getWidth()),append(",")
       .append(height).append("),");
    g.drawRect(1, y, getWidth(), height);
    sb.append("drawRect(").append(1),append(","),append(y).append(",")
       .append(getWidth()),append(","),append(height).append("),");
    g.dispose();
    super.paintComponent(g);
}

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

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