期待 PreconditionError 但得到 NullPointerException

Expecting PreconditionError but got NullPointerException

我有一个 class Natural,在构造方法之前有一个先决条件(注意要求)。

public class Natural {
private int data;

@Requires("n != null")
public Natural(Natural n) {
    this(n.data);
 }
}

这是对该先决条件的测试。它测试构造函数的空输入。

@Test(expected = PreconditionError.class)
public void testConstructorWrong2() {
    Natural n = new Natural(null);
}

测试应该通过,因为该测试预计会违反先决条件。但是我得到的是 NullPonterException。

Cofoja 页面所述:

However, a very important distinction is that constructor preconditions are checked after any call to a parent constructor. This is due to super calls being necessarily the first instruction of any constructor call, making it impossible to insert precondition checks before them. (This is considered a known bug.

以上可能适用于 this 以及 super@Requires 条件只能在 调用 this(n.data); 之后检查,因为 Java 不允许在它之前发生任何事情。因此,在注释甚至有机会检查前提条件之前,对 n.data 的调用会抛出 NullPointerException

如果您仍想检查前提条件,则必须删除对 this(...) 的调用并直接初始化对象

@Requires("n != null")
public Natural(Natural n) {
  this.data = n.data;
}