Java Junit尝试确认返回Null
我有一个额外的学分分配,让我做junit测试,但我不明白如何让我的getDestinations测试返回null。 所以我有这个方法和变量:Java Junit尝试确认返回Null,java,junit,Java,Junit,我有一个额外的学分分配,让我做junit测试,但我不明白如何让我的getDestinations测试返回null。 所以我有这个方法和变量: private final Point3D destination = new Point3D(); public Point3D getDestination() { if (destination == null) { return null; } return new Poin
private final Point3D destination = new Point3D();
public Point3D getDestination() {
if (destination == null) {
return null;
}
return new Point3D(destination);
}
public final void setDestination(Point3D aPoint) throws InvalidDataException {
if (aPoint == null) {
throw new InvalidDataException("Null Point3D sent to setDestination(Point3D)");
}
setDestination(aPoint.getX(), aPoint.getY(), aPoint.getZ());
}
我试图让netbeans知道,当我测试destination=null
时,它返回null
到目前为止,我的测试是:
public void testGetDestination(){
testPoint3D = new Point3D(4.0, 5.0, 6.0);
Point3D p = testMovable.getDestination();
assertEquals(p, testPoint3D);
assertNotNull(p);
}
public void testSetDestination_Point3D() throws Exception {
Point3D newPoint = new Point3D(0.0, 0.0, 0.0);
testMovable.setDestination(newPoint);
Point3D p = new Point3D();
assertNotNull(p);
assertEquals(p, newPoint);
assertNotSame(p, newPoint);
p = null;
try{
testMovable.setDestination(p);
fail("Null Point3D sent to setDestination(Point3D)");
}catch(InvalidDataException ex){
assertEquals(ex.getMessage(),"Null Point3D sent to setDestination(Point3D)");
}
}
但是正如您所看到的,我不能真正调用null而不让它失败/被异常捕获
有办法吗 不,根据您当前的代码,无法使
目的地为null
。具体而言:
private final Point3D destination = new Point3D();
final
修饰符使得目的地
不可能被分配到初始化为的点3d
之外的任何其他值
因此,在getDestination()
方法中,以下代码永远无法到达,应该删除:
if (destination == null) {
return null;
}
你为什么要尝试测试一个不可能的情况?这是一种乐趣。很高兴这有帮助:)