java - 构造函数的 JUnit 测试

标签 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));
}

请帮忙。

最佳答案

我建议您使用模拟库( 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)来检查所有操作是否按预期执行(调用次数、执行顺序...)。

关于java - 构造函数的 JUnit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34065889/

相关文章:

Java 增量 i = i++;

java - 如何确定在 VisualVM 堆转储中实例化对象的位置

android - Robolectric:java.lang.RuntimeException:java.lang.ClassNotFoundException:org.robolectric.android.internal.ParallelUniverse

java - EasyMock/PowerMock导入问题

java - 有什么方法可以对采用 MediaType.MULTIPART_FORM_DATA 进行文件上传的休息服务进行 junit 测试吗?

java - 用正则表达式组合替换子字符串

java - Spring 4 - 带有服务的自定义 SecurityExpression

c# - 模拟 IList 的单元测试方法

Ruby Test :Unit, 如何知道测试套件中每个测试用例的失败/通过状态?

php - 需要执行composer和npm的WordPress插件的集成测试