Junit试图确认Null被退回

时间:2015-03-06 00:31:03

标签: java junit

我有这个额外的信用分配让我做junit测试,但我不明白我如何使我的测试getDestinations返回null。 所以我有这个方法和变量:

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而不会让它失败/被异常捕获。

有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:7)

不,根据您当前的代码,无法使destination成为null。具体做法是:

private final Point3D destination = new Point3D();

final修饰符使destination无法分配给Point3D初始化为getDestination()之外的任何其他值。

因此,在您的 if (destination == null) { return null; } 方法中,永远无法访问以下代码,应将其删除:

{{1}}