【发布时间】:2019-03-24 22:05:43
【问题描述】:
我正在尝试在 JUnit 中构建一个方法来测试对象是否为 Spherocylinder,但我无法实现覆盖。
这是我要测试的条件。
-equals 方法返回 true 的条件
-obj 不是球柱的条件
-对象标签不同的条件
-物体体积不相等的条件
-物体圆柱高度不相等的条件
这是方法,我正在尝试测试。
public boolean equals(Object obj) {
if (!(obj instanceof Spherocylinder)) {
return false;
}
else {
Spherocylinder d = (Spherocylinder) obj;
return (label.equalsIgnoreCase(d.getLabel())
&& Math.abs(radius - d.getRadius()) < 0.000001
&& Math.abs(cylinderHeight - d.getCylinderHeight())
< 0.000001);
}
}
/**
* hashcode method for equals method.
* @return - return 0
*/
public int hashCode() {
return 0;
}
这是我在 Junit 中编写的测试方法
/**A test for equals() method. **/
@Test public void equals() {
Spherocylinder c1 = new Spherocylinder("Small Example", 0.5, 0.25);
Spherocylinder c2 = new Spherocylinder("Different Example", 0.5, 0.25);
Assert.assertFalse(c1.equals(c2));
Spherocylinder d1 = new Spherocylinder("Small Example", 0.5, 0.25);
Spherocylinder d2 = new Spherocylinder("Small Example", 0.6, 0.25);
Assert.assertFalse(d1.equals(d2));
Spherocylinder e1 = new Spherocylinder("Small Example", 0.5, 0.25);
Spherocylinder e2 = new Spherocylinder("Small Example", 0.5, 0.3);
Assert.assertFalse(e1.equals(e2));
Spherocylinder f1 = new Spherocylinder("Small Example", 0.5, 0.25);
Spherocylinder f2 = new Spherocylinder("Small Example", 0.5, 0.25);
Assert.assertEquals(f1, f2);
}
我相信我已经涵盖了除以下情况之外的所有条件
-obj 不是球柱的条件
如何测试这种情况?
【问题讨论】:
-
我认为您可以将
Spherocyliner与任何旧对象(例如字符串)进行比较。 (记住equals()方法将 Object 作为参数,所以你可以传递任何东西。) -
spherocylinder.equals(new Object()) -
并且:不要将所有测试都放在一种方法中。相反,每个条件都有一种测试方法。然后给方法命名,例如 testEqualsWithEqualSpheres。经验法则:每个测试方法一个断言。并考虑使用 assertThat 和 hamcrest 匹配器。
标签: java object junit boolean equals