3

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

问题是该规则需要访问少量的@AutowiredSpring 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 不能很好地结合在一起,或者会有一些乍一看并不明显的问题。

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

4

2 回答 2

1

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

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

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

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

    // ...
}
于 2019-05-28T13:34:52.690 回答
-2

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

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

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

于 2017-07-15T23:56:03.043 回答