尝试在 groovy 文件中创建规则的一些变体,我想到,@Rule 并不描述声明,而是描述分配。 因此,运行者在加载测试时会尝试每条规则以获得正确的分配。
//Correct variants:
@Rule
public ErrorCollector collector1= new ErrorCollector();
public ErrorCollector collector2= null;
@Rule
collector2= new ErrorCollector();
public ErrorCollector collector3;
@Rule
collector3= new ErrorCollector();
// incorrect variants:
@Rule
public ErrorCollector collector4= null;
@Rule
public ErrorCollector collector5;
@Rule
public ErrorCollector collector5=somethingThatIsNotRule;
@Rule
public ErrorCollector collector5=anotherRule;
但是,后来我发现了一些自相矛盾的变体:
//these lines are not only taken by the runner, but also passed without errors:
public ErrorCollector collector6;
{
@Rule
collector6= null;
}
public ErrorCollector collector7=null;
{
@Rule
collector7= null;
}
其逻辑是什么?
这似乎是 Runner 中的一个错误 - Runner 在构建测试之前进行了过多的检查。
最佳答案
在 Java 中,JUnit 运行程序会检查 @Rule
注释是否应用于公共(public)非静态字段或返回 TestRule 的公共(public)非静态方法。或MethodRule .
如果字段或方法上有@Rule
注释,则该值必须是非空值,否则在执行测试期间将得到 NullPointerException。
您的示例比该示例更复杂,因为 Groovy 是一种动态语言,因此它在运行时而不是编译时进行检查。我怀疑 Collector2 和 Collector3 实际上没有做任何事情。 @Rule
注释不适用于该字段。
collector4 => NullPointerException
collector5 => same as collector5
collector5a => when you execute, I suspect Groovy doesn't find the
expected methods on your somethingThatIsNotRule, or
you're getting a ClassCastException or something similar.
collector5b => same as 5b for anotherRule
对于您的悖论,再次强调,@Rule
注释实际上并未应用于该字段。
我怀疑您的困惑来自这样一个事实:Groovy 不会提示在非字段或方法的内容上使用 @Rule
(而 Java 会)。它可能不会提示,但 JUnit 会忽略这样的注释。
关于java - Groovy 类中 @Rule(JUnit) 声明和赋值的逻辑是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15943145/