测试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");
    }
}

解决方法

由于您要在函数开头访问x的属性yotherPoint,因此,如果otherPoint为null,它将抛出NullPointerException而不是IllegalArgumentException 。为了在otherPointnull时抛出IllegalArgumentException,需要在访问属性x和{{1之前,在if语句中将null检入到函数的开头。 }}

y