【发布时间】: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