Cucumber集成测试已配置@CucumberContextConfiguration仍报错如何解决
问题描述
在对Restful API做Cucumber集成测试时,已按照异常提示添加@CucumberContextConfiguration注解配置,但运行测试仍抛出如下异常:
io.cucumber.core.backend.CucumberBackendException: Please annotate a glue class with some context configuration.
现有配置如下:
1. VehicleRegApplicationTests.java(测试启动类)
import io.cucumber.junit.Cucumber; import io.cucumber.junit.CucumberOptions; import io.cucumber.spring.CucumberContextConfiguration; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; @RunWith(Cucumber.class) @CucumberContextConfiguration @SpringBootTest(classes = {VehicleRegApplication.class, VehicleRegApplicationTests.class, CucumberSpringConfiguration.class}) @CucumberOptions(features = "src/test/resources/Features", glue = {"com.vehiclereg.StepDefinitions"}, plugin = {"pretty"}) public class VehicleRegApplicationTests { @Test void contextLoads() { } }
2. CucumberSpringConfiguration.java(上下文配置类,与启动类同目录)
import io.cucumber.spring.CucumberContextConfiguration; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; @CucumberContextConfiguration @SpringBootTest @AutoConfigureMockMvc public class CucumberSpringConfiguration { }
已引入依赖:cucumber-java、cucumber-spring、cucumber-junit、junit。
问题原因与修复方案
核心问题1:glue扫描路径不包含配置类
Cucumber只会扫描glue属性指定的包下的类,你当前的glue只配置了com.vehiclereg.StepDefinitions,如果CucumberSpringConfiguration不在这个包下,Cucumber就无法识别到带@CucumberContextConfiguration的配置类。
修复:将配置类所在的包添加到glue路径中,示例如下:
@CucumberOptions(features = "src/test/resources/Features", // 替换为你的配置类实际所在的包路径 glue = {"com.vehiclereg.StepDefinitions", "com.vehiclereg"}, plugin = {"pretty"})
问题2:冗余的@CucumberContextConfiguration注解
你在VehicleRegApplicationTests和CucumberSpringConfiguration两个类上都加了@CucumberContextConfiguration,属于冗余配置,容易引发上下文冲突。
修复:删除VehicleRegApplicationTests类上的@CucumberContextConfiguration注解,只在专门的配置类CucumberSpringConfiguration上保留即可。
问题3:JUnit版本混用
你使用了JUnit 4的@RunWith(Cucumber.class)注解,但测试类中的contextLoads方法使用的是JUnit 5的@org.junit.jupiter.api.Test注解,版本混用可能导致上下文加载异常。
修复:统一JUnit版本,如果使用JUnit 4运行Cucumber,将@Test替换为org.junit.Test;如果使用JUnit 5,替换cucumber-junit依赖为cucumber-junit-platform-engine,并去掉@RunWith注解,使用JUnit 5的测试启动方式。
额外检查项
确保所有cucumber相关依赖的版本完全一致,避免版本不兼容导致的异常。
内容的提问来源于stack exchange,提问作者SHY.John

