我正在创建一个Fraction API类,我的一个构造函数通过将分子和分母参数放在最低的术语中来标准化一个分数:
$a = 4;
$b = &$a;
$b = 5;
// $a = 5, $b = 5
我想测试构造函数在分母为0时抛出ArithmeticException。据我所知,JUnit 5不支持<?php
session_start();
$fruit = &$_SESSION['fruit'];
if (!isset($fruit))
$fruit = array("Pear", "Apple", "Orange");
//...
但使用 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
}
}
。
我的测试:
@Test(expected = ArithmeticException.class
不起作用,IntelliJ说'分数与可执行文件不兼容'。
如何测试构造函数是否抛出异常?
由于
答案 0 :(得分:7)
以下是为JUnit 5 Executable
传递 lambda 的语法:
assertThrows(ArithmeticException.class, () -> new Fraction(2, 0));
您无需将结果分配给f
,因为您知道该方法无法完成。