如何测试构造函数是否使用JUnit 5抛出异常?

Tob*_*own 1 java unit-testing junit5

我正在创建一个Fraction 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

    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

不起作用,IntelliJ说'分数与可执行文件不兼容'.

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

谢谢

das*_*ght 7

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

assertThrows(ArithmeticException.class, () -> new Fraction(2, 0));
Run Code Online (Sandbox Code Playgroud)

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