[英]Why does my function keep failing my JUnit test?
This is one of my classes that I am testing. 这是我正在测试的课程之一。 It keeps failing the calculateVolume() method and I am not sure why. 它一直使calculateVolume()方法失败,我不确定为什么。
package shape3D;
public class Sphere implements Cloneable {
private double myRadius;
private double myVolume;
private double mySurfaceArea;
private final static double pi = 3.14;
public static void main(String args[]){
Sphere sphere = new Sphere();
}
public double calculateVolume(){
myVolume = (4/3)*pi*(Math.pow(myRadius,3));
return myVolume;
}
public double calculateSurfaceArea(){
mySurfaceArea = ((4)*(pi)*(Math.pow(myRadius,2)));
return mySurfaceArea;
}
public double getSurfaceArea(){
return this.calculateSurfaceArea();
}
public double getVolume(){
return this.calculateVolume();
}
public void setRadius(double radius2){
myRadius = radius2;
}
public String toString(){
return "Volume: " + this.getVolume() + " Surface area " + this.getSurfaceArea();
}
public Sphere clone (){
Sphere p = new Sphere();
p.setRadius(myRadius);
return p;
}
}
Here is the JUnit test case I am using 这是我正在使用的JUnit测试用例
public class sphereTest {
@Test
public void testSphere(){
shape3D.Sphere sphere = new shape3D.Sphere();
sphere.setRadius(6);
assertTrue(sphere.calculateSurfaceArea()== 452.16);
assertTrue(sphere.calculateVolume()== 904.32);
The calculateSurfaceArea() stuff passes fine but the volume is failing and I am not sure why. computeSurfaceArea()东西通过得很好,但是卷失败了,我不确定为什么。
You're doing integer division when calculating the volume truncating the first term of the equation to 1
. 你计算体积截断方程式的第一项时做整数除法1
。 Replace 更换
myVolume = (4 / 3) * pi * (Math.pow(myRadius, 3)); // 678.24
with 与
myVolume = (4 / 3.0) * pi * (Math.pow(myRadius, 3)); // 904.31
Due to floating point imprecision you will still need to allow for the difference between the expected & calculated values. 由于浮点数的不精确性,您仍然需要考虑期望值和计算值之间的差异。 You can use this version of assertEquals
which allows a delta value to do the comparison - replace 您可以使用此版本的assertEquals
允许使用增量值进行比较-替换
assertTrue(sphere.calculateVolume()== 904.32);
with 与
assertEquals(sphere.calculateVolume(), 904.32, .02);
The calculation 计算
myVolume = (4/3)*pi*(Math.pow(myRadius,3));
Uses integer arithmetic: 4/3
evaluates to 1
. 使用整数运算: 4/3
计算为1
。
Change it to 更改为
myVolume = (4.0/3)*pi*(Math.pow(myRadius,3));
Quite aside from the 4/3 integer problem (which I failed to spot): It's not safe to compare two Java double values this way. 除了4/3整数问题(我没有发现)之外,它还比较:用这种方法比较两个Java double值并不安全。
If you use assertEquals
instead of assertTrue
then you might see the problem. 如果使用assertEquals
而不是assertTrue
则可能会看到问题。 I'm betting that it's calculating 4/3 first, then truncating it. 我敢打赌,它先计算4/3,然后将其截断。 And it'll still do this even if you make those into doubles. 即使将它们变成双倍,它仍然会这样做。
Use the overload for assertEquals as mentioned in this question . 如本问题所述,将重载用于assertEquals。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.