【发布时间】: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