我需要为此构造函数编写单元测试,我已经为 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));
}
请帮忙。
最佳答案
我建议您使用模拟库( EasyMock 、 Mockito 等),或者您只需扩展 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
的实例传递给构造函数,然后检查构造的对象是否确实具有正确的 width
、height
和 RGB
值。
您还可以添加一些行为验证方法(例如示例中的 verifyCalled
)来检查所有操作是否按预期执行(调用次数、执行顺序...)。
关于java - 构造函数的 JUnit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34065889/