【问题标题】:Spring dependencies not injected for Cucumber runner没有为 Cucumber runner 注入 Spring 依赖项
【发布时间】:2026-02-09 03:30:01
【问题描述】:

我有使用 SpringJUnit4ClassRunner 的现有测试用例,这些测试用例使用 @Resource 注释来标记要注入的变量。

@Resource 被用作将来可能使用的另一个 DI 框架。 (@Resource vs @Autowired)

现在我已经开始使用 Cucumber 运行器编写 BDD 测试用例。然而,DI 似乎没有发生。 (@Autowired 有效,但 @Resource 无效)有人知道为什么不吗?

【问题讨论】:

  • 根据链接Resource vs Autowired,自春季 3.0 起不建议使用它们 - 因此请考虑从 JSR-330 转到 interface Inject 注释。

标签: java spring dependency-injection bdd cucumber-jvm


【解决方案1】:

(我假设您使用的是 Cucumber-JVM)

您应该使用 Cucumber 运行器,而不是使用 SpringJUnit4ClassRunner

@RunWith(Cucumber.class)

要使用它,您需要以下依赖项:

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>${info.cukes.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-junit</artifactId>
        <version>${info.cukes.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-spring</artifactId>
        <version>${info.cukes.version}</version>
        <scope>test</scope>
    </dependency>

这将在您的类路径中查找 cucumber.xml。这个 XML 只是一个 spring bean 配置 XML。我的很简单,包含:

<context:component-scan base-package="cucumber.runtime.java.spring"/>
<context:annotation-config/>

<!-- wire beans required for testing -->
<import resource="classpath*:/context.xml"/>

当您运行测试时,您应该会看到 Spring 加载 cucumber.xml,然后导入 context.xml

【讨论】:

    最近更新 更多