测试 IllegalArgumentException 时遇到问题

Trouble with testing IllegalArgumentException

我在通过 IllegalArgumentException 测试时遇到了问题。当没有对象被传递到我的方法中时,IllegalArgumentException 将不会发生。

public double distanceTo(Point otherPoint) {
    int x = (otherPoint.x - this.x);
    int y = (otherPoint.y - this.y);
    double xDbl = Math.pow(x, 2);
    double yDbl = Math.pow(y, 2);
    if (otherPoint!=null) {
        return Math.hypot(xDbl,yDbl);
    } else {
        throw new IllegalArgumentException("No value for otherPoint object");
    }
}

由于您在函数开头访问 otherPoint 的属性 xy,如果 otherPoint 为 null,它将抛出 NullPointerException非法参数异常。为了在 otherPointnull 时抛出 IllegalArgumentException,您需要在访问属性 x 和 [=12] 之前将 if 语句中的 null 检查带到函数的开头=]

public double distanceTo(Point otherPoint) {
    if (otherPoint==null) {
        throw new IllegalArgumentException("No value for otherPoint object");
    }
    int x = (otherPoint.x - this.x);
    int y = (otherPoint.y - this.y);
    double xDbl = Math.pow(x, 2);
    double yDbl = Math.pow(y, 2);
    return Math.hypot(xDbl,yDbl); 
}