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

Spring Boot Cucumber测试中AccountRepository注入为空问题求助

问题根源

你在Cucumber步骤定义里直接new AccountService(),这个实例不属于Spring容器管理,导致AccountService里的@Autowired AccountRepository无法被Spring注入,最终触发空指针异常。而正常运行时,AccountService是Spring托管的Bean,依赖注入能正常工作。

解决方案

1. 配置Cucumber与Spring上下文整合

创建Cucumber测试配置类,让Cucumber加载Spring Boot上下文:

import org.springframework.boot.test.context.SpringBootTest;
import io.cucumber.spring.CucumberContextConfiguration;

@CucumberContextConfiguration
@SpringBootTest
public class CucumberSpringConfig {
}

2. 让步骤类纳入Spring管理并注入依赖

修改你的步骤定义类database.java,不要手动new服务类,而是通过Spring注入:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import io.cucumber.java.en.Given;
import static org.junit.Assert.assertTrue;

// 标记为Spring组件,让Spring管理该类
@Component
public class DatabaseSteps {

    private final AccountService accountService;

    // 构造器注入(比字段注入更安全,推荐使用)
    @Autowired
    public DatabaseSteps(AccountService accountService) {
        this.accountService = accountService;
    }

    @Given("Database is not empty")
    public void databaseIsNotEmpty() {
        assertTrue(accountService.getAccountsCount() != 0);
    }
}

3. 优化Service的注入方式(可选但推荐)

把AccountService的字段注入改成构造器注入,避免依赖注入相关隐患,同时提升代码可测试性:

import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class AccountService {

    private final AccountRepository accountRepository;

    // 构造器注入,Spring会自动装配AccountRepository
    public AccountService(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }

    public List<AccountEntity> getAllAccounts() {
        return accountRepository.findAll();
    }

    public AccountEntity getAccountById(Long id) {
        return accountRepository.findById(id).orElse(null);
    }

    public Long getAccountsCount() { 
        return accountRepository.count(); 
    }
}

内容的提问来源于stack exchange,提问作者None

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 19:42:09