Junit试图确认Null被退回

Yum*_*ree 2 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());
    }
Run Code Online (Sandbox Code Playgroud)

我试图让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)");
        }
    }
Run Code Online (Sandbox Code Playgroud)

但正如你所看到的,我不能真正调用null而不会让它失败/被异常捕获.

有办法解决这个问题吗?

gkn*_*ker 7

没有,有没有办法使destinationnull,鉴于你目前的代码.特别:

private final Point3D destination = new Point3D();
Run Code Online (Sandbox Code Playgroud)

final修饰使得它不可能destination永远被分配到其他任何值除了Point3D它的初始化.

因此,在您的getDestination()方法中,永远不会到达以下代码,应该删除它们:

    if (destination == null) {
        return null;
    }
Run Code Online (Sandbox Code Playgroud)