IntelliJ单元测试配置中Lombok@RequiredArgsConstructor初始化失败
问题描述
在IntelliJ中以单元测试配置运行项目时,遇到以下错误:
/Users/francislainycampos/IdeaProjects/so-be-automation/src/test/java/com/francislainy/sobeautomation/steps/MySteps.java:14:30 java: variable restClient not initialized in the default constructor
但在终端执行mvn test时,相同的测试却能正常运行。
我的环境配置
RestClient.java
@Slf4j @Component @AllArgsConstructor public class RestClient { public RequestSpecification getRequestSpecification() { // Rest Assured config here } }
CucumberSpringConfiguration.java
@CucumberContextConfiguration @SpringBootTest(classes = TestConfig.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class CucumberSpringConfiguration {}
TestConfig.java
@ComponentScan(basePackages = {"com.francislainy.sobeautomation"}) @EnableAutoConfiguration public class TestConfig {}
MySteps.java
@RequiredArgsConstructor public class MySteps { private final RestClient restClient; private Response response; @Given("I send a GET request to the Bored API") public void iSendAGETRequestToTheBoredAPI() { response = restClient.getRequestSpecification().get("https://www.boredapi.com/api/activity"); } }
pom.xml (相关依赖)
<dependencies> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>io.cucumber</groupId> <artifactId>cucumber-spring</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
已尝试的解决方案
- 检查Lombok注解处理:已在IntelliJ中启用注解处理(
Settings > Build, Execution, Deployment > Compiler > Annotation Processors)。 - 手动添加构造函数:在
MySteps.java中显式定义构造函数后,问题解决。 - 修改Lombok依赖作用域:将其改为
compile或不指定默认作用域。 - 尝试不同版本:测试了Lombok 1.18.30及最新版本1.18.36。
临时解决方法
移除@RequiredArgsConstructor,为变量显式定义构造函数:
public class MySteps { private final RestClient restClient; private Response response; public MySteps(RestClient restClient) { this.restClient = restClient; } }
疑问
为什么在IntelliJ的单元测试配置中运行时,@RequiredArgsConstructor无法初始化restClient,但mvn test却能正常工作?有没有办法让Lombok生成的构造函数在两种场景下都正常运行?
内容的提问来源于stack exchange,提问作者Francislainy Campos
相关产品推荐
相关产品推荐

