【问题标题】:Autowire JUnit rule in integration test集成测试中的 Autowire JUnit 规则
【发布时间】:2017-12-20 18:44:37
【问题描述】:

我有一段代码将在多个集成测试中重复。代码将在测试之前和之后运行。我已经决定使用 JUnit @Rule 将是实现这一目标的最佳方式。

问题是规则需要访问少数@Autowired Spring bean。 (测试使用 Spring Integration Test Runner 运行,因此 Autowire 可以正常工作。

我有一个规则:

public class CustomSpringRule extends ExternalResource {
    private final SomeOtherBean someOtherBean;

    public CustomSpringRule(SomeOtherBean someOtherBean) {
        this.someOtherBean = someOtherBean;
    }

    @Override
    public void before() {
        someOtherBean.someMethod();
    }

    // ...
}

我已经将我的 bean 添加到我的上下文中:

@Bean 
public CustomSpringRule getCustomSpringRule(SomeOtherBean someOtherBean) {
   return new CustomSpringRule(someOtherBean);
}

最后,我刚刚在测试文件中自动装配了规则 bean:

@Autowire
@Rule
public CustomSpringRule customSpringRule;

一切正常,但我从未真正使用过@Rule 注释,而且我有点担心 JUnit 反射和 Spring Autowire 不能很好地结合在一起,或者会有一些乍一看并不明显的问题。

有人对这是否有效和安全有任何建议吗?

【问题讨论】:

  • 让测试需要按特定顺序运行似乎有点代码味道。测试应该相互独立
  • @Robbo_UK OP 没有说任何关于运行测试的内容是一定的。

标签: spring junit autowired spring-test junit-rule


【解决方案1】:

使用自动连接规则很好 - 这种方法没有问题或限制。

注意:我正在使用组件扫描(例如在@SpringBootTest 中启用),您可以像这样简化规则实现:

@Component
public class CustomSpringRule extends ExternalResource {
    @Autowired
    private SomeOtherBean someOtherBean;

    @Override
    public void before() {
        someOtherBean.someMethod();
    }

    // ...
}

【讨论】:

    【解决方案2】:

    我认为你在这里不需要@Rule,

    “我有一段代码将在多个 集成测试。代码将在测试前后运行。”

    这可以使用 JUnit 的 @Before 和 @After 注解来实现。使用这些注释注释的方法将在每次测试之前/之后执行。所以你可以从这些方法中调用你的通用代码。

    【讨论】:

    • 是的,虽然我想避免代码重复并有一个整洁的规则,但我可以。另一方面,我不确定是否应该使用 spring bean 来做一些测试逻辑。
    • 好吧,我的意思是将您的通用代码保存在测试之外的其他地方,以便您可以在所有测试中使用它。只有调用它才会被重复,就像你上面提到的“someOtherBean.someMethod();”
    猜你喜欢
    • 2013-06-15
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-29
    相关资源
    最近更新 更多