【问题标题】:How to test that a constructor throws an exception using JUnit 5?如何使用 JUnit 5 测试构造函数是否引发异常?
【发布时间】:2018-06-16 04:21:19
【问题描述】:

我正在创建一个分数 API 类,我的一个构造函数通过将分子和分母参数放在最低术语中来规范化分数:

    public Fraction(int numerator, int denominator){
    if (denominator == 0)
        throw new ArithmeticException("Cannot divide by zero.");
    else {
        if (denominator < 0) {
            numerator = -numerator;
            denominator = -denominator;
        }
        int gcd; // Greatest Common Divisor
        int tmpNum = numerator, tmpDen = denominator;
        // Determine greatest common divisor of numerator and denominator
        while (tmpNum != 0 && tmpDen != 0) {
            int tmp = tmpDen;
            tmpDen = tmpNum % tmpDen;
            tmpNum = tmp;
        }
        gcd = Math.abs(tmpNum + tmpDen);
        this.numerator = numerator / gcd; // Assign numerator in its lowest term
        this.denominator = denominator / gcd; // Assign denominator in its lowest term

    }
}

我想测试当分母为 0 时构造函数是否抛出 ArithmeticException。据我所知,JUnit 5 不支持@Test(expected = ArithmeticException.class,但使用assertThrows()。 我的测试:

@Test
public void testZeroDenominator(){
    Fraction f;
    assertThrows(ArithmeticException.class, f = new Fraction(2, 0));
}

不起作用,IntelliJ 说“分数与可执行文件不兼容”。

如何测试构造函数是否抛出异常?

谢谢

【问题讨论】:

    标签: java unit-testing junit5


    【解决方案1】:

    这是为 JUnit 5 的 Executable 传递 lambda 的语法:

    assertThrows(ArithmeticException.class, () -> new Fraction(2, 0));
    

    您不需要将结果分配给f,因为您知道该方法不会完成。

    【讨论】:

    • Ahh Executable 是一个接口,因此 lambda 只是为了掌握接口。是的,这很愚蠢,因为它不会完成,因为它不会分配。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-01-16
    • 1970-01-01
    • 1970-01-01
    • 2010-09-12
    • 2013-09-28
    • 2020-11-05
    相关资源
    最近更新 更多