我有一段代码将在多个集成测试中重复。代码将在测试之前和之后运行。我已经决定使用 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 不能很好地结合在一起,或者会有一些乍一看并不明显的问题。
有人对这是否有效和安全有任何建议吗?