You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 12:56:04