如何解决测试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
的属性y
,otherPoint
,因此,如果otherPoint
为null,它将抛出NullPointerException而不是IllegalArgumentException 。为了在otherPoint
为null
时抛出IllegalArgumentException,需要在访问属性x
和{{1之前,在if语句中将null检入到函数的开头。 }}
y
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。