gpt4 book ai didi

spring - 集成测试中的 Autowire JUnit 规则

转载 作者:行者123 更新时间:2023-12-05 08:08:55 24 4
gpt4 key购买 nike

我有一段代码将在多个集成测试中重复出现。该代码将在测试前后运行。我决定使用 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();
}

// ...
}

关于spring - 集成测试中的 Autowire JUnit 规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45123739/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com