Cucumber整合Spring Boot运行报错:请为Glue类添加上下文配置
解决方案
1. 确保Glue类或测试运行器带有Spring上下文配置
这个错误的核心是Cucumber找不到Spring上下文的配置信息,你需要给Glue类(步骤定义类)或Cucumber测试运行器类添加Spring相关注解:
- 方式一:在测试运行器类上添加配置
import org.junit.platform.suite.api.*; import org.springframework.boot.test.context.SpringBootTest; import static io.cucumber.junit.platform.engine.Constants.*; @Suite @IncludeEngines("cucumber") @SelectPackages("com.your.project") @ConfigurationParameter(key = GLUE_PROPERTY_NAME, value = "com.your.project.steps") @SpringBootTest(classes = YourSpringBootApplication.class) // 替换为你的启动类 public class CucumberTestRunner { } - 方式二:在步骤定义类上添加配置
import org.springframework.boot.test.context.SpringBootTest; import io.cucumber.java.en.Given; @SpringBootTest(classes = YourSpringBootApplication.class) public class UserStepDefinitions { @Given("用户打开登录页面") public void userOpensLoginPage() { // 步骤逻辑 } }
2. 验证依赖版本兼容性
确保Cucumber与Spring Boot版本匹配,避免依赖冲突,POM.xml中需包含正确的整合依赖:
<dependencies> <!-- Cucumber Spring整合依赖 --> <dependency> <groupId>io.cucumber</groupId> <artifactId>cucumber-spring</artifactId> <version>7.14.0</version> <scope>test</scope> </dependency> <!-- Cucumber JUnit平台引擎 --> <dependency> <groupId>io.cucumber</groupId> <artifactId>cucumber-junit-platform-engine</artifactId> <version>7.14.0</version> <scope>test</scope> </dependency> <!-- Spring Boot测试依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies>
注意:如果用Spring Boot 3.x,必须使用Cucumber 7.10.0及以上版本,因为Spring Boot 3基于Jakarta EE规范。
3. 确认Glue路径配置正确
检查Cucumber的GLUE_PROPERTY_NAME配置,确保指向的包包含带有Spring注解的类。如果步骤定义类和Spring配置类分属不同包,需要同时指定多个包:
@ConfigurationParameter(key = GLUE_PROPERTY_NAME, value = "com.your.project.steps, com.your.project.config")
4. 重置IntelliJ运行配置
有时候IntelliJ的自定义运行配置会覆盖参数,导致配置失效:
- 删除现有CucumberTestRunner的运行配置
- 右键点击CucumberTestRunner类,选择"Run 'CucumberTestRunner'",让IDE自动生成默认配置
内容的提问来源于stack exchange,提问作者Alok
相关产品推荐
相关产品推荐

