【问题标题】:What is the logic of @Rule(JUnit) declaration and assignment in a Groovy classGroovy 类中@Rule(JUnit) 声明和赋值的逻辑是什么
【发布时间】:2013-04-11 07:38:07
【问题描述】:

尝试在 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 在构建测试之前进行了过多的检查。

【问题讨论】:

  • 不可能,如果你看一下@Rule 注释,它的目标是FILED&METHOD。您的矛盾变体不应编译,因为本质上它是实例初始化程序块内的字段分配,而不是字段声明。
  • 好吧,我只能假设 Eclipse 编译器中存在错误。这段代码在 IntelliJ Idea 中无法编译
  • 是的,对不起,我忘了提到这一切都是在 groovy 文件中完成的——groovy 不像 java 那样严格——已编辑。

标签: java groovy junit junit-rule junit-runner


【解决方案1】:

在 Java 中,JUnit 运行器检查 @Rule 注释是否应用于公共非静态字段或公共非静态方法,该方法返回 TestRuleMethodRule

如果字段或方法上有@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 会忽略这样的注释。

【讨论】:

猜你喜欢
  • 2010-10-14
  • 2010-10-14
  • 2018-09-14
  • 2020-02-07
  • 1970-01-01
  • 2010-12-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多