在集成测试中自动装配JUnit规则

问题描述 投票:0回答:1

我有一段代码将在多个集成测试中重复。代码将在测试之前和之后运行。我已经决定使用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不能很好地结合在一起,或者会出现一些初看起来不明显的问题。

有人建议这是否有效且安全吗?

java spring junit autowired rule
1个回答
0
投票

我觉得你不需要@Rule,

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

这可以使用JUnit的@Before和@After注释来实现。使用这些注释注释的方法将在每次测试之前/之后执行。所以你可以用这些方法调用你的公共代码。


0
投票

使用自动连线规则很好 - 这种方法没有任何问题或限制。

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

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

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

    // ...
}
© www.soinside.com 2019 - 2024. All rights reserved.