测试 IllegalArgumentException 出现问题

huangapple go评论78阅读模式
英文:

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("未提供otherPoint对象的值");
    }
}
英文:

I am having trouble with passing tests for my IllegalArgumentException. When no object is passed into my method, the IllegalArgumentException will not happen.

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

答案1

得分: 1

代码部分不需要翻译,这里是翻译后的内容:

由于在函数开始时访问了otherPoint的属性xy,如果otherPoint为null,它将抛出NullPointerException而不是IllegalArgumentException。为了在otherPoint为null时抛出IllegalArgumentException,您需要将null检查放在函数的开头,即在访问属性xy之前。

public double distanceTo(Point otherPoint) {
    if (otherPoint == null) {
        throw new IllegalArgumentException("没有提供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);
    return Math.hypot(xDbl, yDbl); 
}
英文:

Since you're accessing properties x, y of otherPoint at the beginning of the function, if otherPoint is null, it will throw the NullPointerException instead of IllegalArgumentException. In order to throw the IllegalArgumentException when otherPoint is null, you need to bring your null check in the if statement to the beginning of the function, before accessing the properties x and y

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); 
}

huangapple
  • 本文由 发表于 2020年10月4日 12:11:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/64191080.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定