我有一段代码将在多个集成测试中重复出现。该代码将在测试前后运行。我决定使用 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);
}
最后,我刚刚在测试文件中 Autowiring 了规则 bean:
@Autowire
@Rule
public CustomSpringRule customSpringRule;
一切正常,但我从未真正使用过 @Rule
注释,我有点担心 JUnit 反射和 Spring Autowire 不能很好地结合在一起,或者会有一些不明显的问题乍一看。
有人对这是否有效和安全有任何建议吗?
最佳答案
使用自动连接的规则很好——这种方法没有问题或限制。
注意:如果您正在使用组件扫描(例如在 @SpringBootTest
中启用),您可以像这样简化规则实现:
@Component
public class CustomSpringRule extends ExternalResource {
@Autowired
private SomeOtherBean someOtherBean;
@Override
public void before() {
someOtherBean.someMethod();
}
// ...
}
https://stackoverflow.com/questions/45123739/
相关文章:
python - 管道输入错误 "Input Contains NaN"
android - setMultiChoiceItems 对话框中的图标 - Android
ios - react-native-maps 为每个区域填充颜色
sql - 使用 SQL 查询将 Excel 数据加载到 Azure SQL 中
angularjs - headless Chrome : chrome not reachable
java - Hibernate ManyToOne 保存对象
bash - 如何在 Powerline-Plain [Bash-it] 主题的提示中显示彩色主机名