如何使用 JUnit 5 测试构造函数是否抛出异常?
How to test that a constructor throws an exception using JUnit 5?
我正在制作一个分数 API class,我的一个构造函数通过将分子和分母参数置于最低项来标准化分数:
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 说 'Fraction is not compatible with Executable'。
如何测试构造函数是否抛出异常?
谢谢
这是为 JUnit 5 Executable
传递 lambda 的语法:
assertThrows(ArithmeticException.class, () -> new Fraction(2, 0));
您不需要将结果分配给 f
,因为您知道该方法不会完成。
我正在制作一个分数 API class,我的一个构造函数通过将分子和分母参数置于最低项来标准化分数:
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 说 'Fraction is not compatible with Executable'。
如何测试构造函数是否抛出异常?
谢谢
这是为 JUnit 5 Executable
传递 lambda 的语法:
assertThrows(ArithmeticException.class, () -> new Fraction(2, 0));
您不需要将结果分配给 f
,因为您知道该方法不会完成。