我正在对正在进行的项目进行JUnit测试,然后碰到了墙壁测试以下方法:
public boolean equals(Object obj) {
if (!(obj instanceof Vehicle)) {
return false;
}
else {
Vehicle other = (Vehicle) obj;
return (owner + yearMakeModel + value).
equals(other.owner + other.yearMakeModel
+ other.value);
我正在使用以下测试来测试instnaceof,但是,它似乎并未测试正确的代码。提交后,代码的这一部分将突出显示,并且我看到一条消息,表明我的测试未执行此方法。
/**
* instanceof test false.
*/
@Test public void instanceOfFalseTest() {
Car car1 = new Car("Jones, Sam", "2017 Honda Accord", 222000, true);
Object obj = new Object();
Assert.assertFalse(obj instanceof Vehicle);
}
/**
* instanceof test true.
*/
@Test public void instanceOfTrueTest() {
Car car1 = new Car("Jones, Sam", "2017 Honda Accord", 222000, true);
Object obj = new Object();
Assert.assertTrue(car1 instanceof(Vehicle);
答案 0 :(得分:2)
无需测试Java的instanceof
运算符,
因为它是JVM的内置功能,而不是您开发的。
您应该测试您的equals
方法。
例如这样的
@Test public void equalsFalseTest1() {
Car car1 = new Car("Jones, Sam", "2017 Honda Accord", 222000, true);
Object obj = new Object();
Assert.assertNotEquals(car1, obj);
}
@Test public void equalsFalseTest2() {
Car car1 = new Car("Jones, Sam", "2017 Honda Accord", 222000, true);
Car car2 = new Car("Doe, John", "2017 Honda Accord", 222000, true);
Assert.assertNotEquals(car1, car2);
}
@Test public void equalsTrueTest() {
Car car1 = new Car("Jones, Sam", "2017 Honda Accord", 222000, true);
Car car2 = new Car("Jones, Sam", "2017 Honda Accord", 222000, true);
Assert.assertEquals(car1, car2);
}
然后实际调用您的equals
方法。
答案 1 :(得分:2)
Nikolas的另一个答案很好地解释了为什么您当前的测试毫无意义。一个更合理的测试可能看起来像这样:
Car car1 = new Car("Jones, Sam", "2017 Honda Accord", 222000, true);
Car car2 = new Car("Jones, Sam", "2017 Honda Accord", 222000, true);
Car car3 = new Car("Jones, Samual", "2017 Honda Accord", 222000, true);
assertThat(car1, is(car2));
assertThat(car1, not(car3));
其中is()
指的是Java Hamcrest匹配器(它们允许您以非常优雅的方式写下测试用例)。
您想想出所有可能的方式,如何使两个对象相等,或者不相等。然后,您(至少)对于每个用例都需要一个测试用例。理想情况下,它们各自进入单独的独立@Test方法。
答案 2 :(得分:0)
另一个答案:
@Test public void instanceOfFalseTest() {
Object obj = new Object();
assertThat(obj, instanceOf(Vehicle.class));
}
@Test public void instanceOfTrueTest() {
Car car1 = new Car("Jones, Sam", "2017 Honda Accord", 222000, true);
Object obj = new Object();
assertThat(car1, instanceOf(Vehicle.class));
}
,其中instanceOf()检查对象是否为给定类的实例。
点击参考hamcrest instanceOf()