Junit 试图确认返回 Null

Junit trying to confirm Null is returned

我有这个额外的学分分配让我进行 junit 测试,但我不明白如何让我的 getDestinations return 测试为空。 所以我有这个方法和变量:

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 时 return 为空。

她是我目前为止的测试:

   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)");
        }
    }

但是如您所见,如果不通过异常 fail/caught 调用 null,我将无法真正调用它。

有办法解决这个问题吗?

不,根据您当前的代码,无法使 destination 变为 null。具体来说:

private final Point3D destination = new Point3D();

final 修饰符使得 destination 不可能被分配给除了 Point3D 之外的任何其他值它被初始化。

因此在您的 getDestination() 方法中,永远无法访问以下代码,应该将其删除:

    if (destination == null) {
        return null;
    }