构造函数的JUnit测试

时间:2015-12-03 12:17:39

标签: java unit-testing junit

我需要为这个构造函数编写单元测试,我已经为BufferedImage图像为null时的情况编写了一个单元测试:

@Test(expected = NullPointerException.class)
public void testConstructorNull(){        
    bfImage = null;
    ColorImage cImage = null;
    assertNotNull(cImage = new ColorImage(bfImage));
}

,但我不确定如何在一切正常的情况下编写测试

public ColorImage(BufferedImage image)
{
    super(image.getWidth(), image.getHeight(), TYPE_INT_RGB);
    int width = image.getWidth();
    int height = image.getHeight();
    for (int y=0; y<height; y++)
        for (int x=0; x<width; x++)
            setRGB(x, y, image.getRGB(x,y));
}

请帮忙。

2 个答案:

答案 0 :(得分:0)

我建议您使用模拟库(EasyMockMockito等),否则您只需扩展BufferedImage以使其返回某些预期值和/或验证正确执行调用,例如:

public class MockBufferedImage extends BufferedImage {

    private int calledGetWidth, calledGetHeight;
    private int calledGetRGB;

    public MockBufferedImage() {
        super(10, 10, BufferedImage.TYPE_INT_RGB);
    }

    @Override
    public int getWidth() {
        calledGetWidth++;
        return super.getWidth();
    }

    @Override
    public int getHeight() {
        calledGetHeight++;
        return super.getHeight();
    }

    @Override
    public int getRGB(int x, int y) {
        calledGetRGB++;
        return 0xff00ff;
    }

    // An example method verifier, just for show!
    public void verifyCalled(int times) {
        assertThat(calledGetWidth, is(times));
        assertThat(calledGetHeight, is(times));
        assertThat(calledGetRGB, is(times * 100));
    }
}

然后,您可以将MockBufferedImage的实例传递给构造函数,然后检查您构造的对象确实具有widthheightRGB的正确值。

您还可以添加一些行为验证方法(例如示例中的verifyCalled),以检查是否按预期执行的所有操作(调用的次数,执行顺序......)。

答案 1 :(得分:0)

只需检查创建的实例是否处于预期状态。

这意味着由你来决定。它看起来你将一些像素设置为值,也许可以在断言中使用这些像素来检查某个像素是否真的得到了适当的设置。

请注意,这不仅测试构造函数,还测试setRGB和假定的acsessor。这对于测试来说实际上是一件好事,因为它避免了通过首先使用类来测试我们想要从外部隐藏的内部状态。

相关问题