我有这个额外的学分分配让我进行 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 而不让它失败/被异常捕获。
有办法解决这个问题吗?
最佳答案
不,根据您当前的代码,没有办法使 destination
为 null
。具体来说:
private final Point3D destination = new Point3D();
final
修饰符使得 destination
不可能被分配给除初始化为 Point3D
之外的任何其他值。
因此在您的getDestination()
方法中,永远无法访问以下代码,应该将其删除:
if (destination == null) {
return null;
}
关于java - Junit 试图确认返回 Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28890419/