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

Spring Boot集成测试中注入真实依赖的问题排查

问题原因与解决方案

问题根源

你的测试类没有触发Spring Boot的上下文初始化,@Inject注解完全未生效,导致所有依赖字段为null,手动创建PasswordService时自然抛出空指针异常。

修复步骤

  1. 启用Spring Boot测试上下文:在测试类上添加@SpringBootTest注解,该注解会启动完整的Spring应用上下文,让Spring接管依赖注入逻辑。
  2. 直接注入目标Service:无需手动实例化PasswordService,Spring会自动将其所有真实依赖(包括BCryptPasswordEncoder、PasswordGenerator、CharacterCharacteristicsRule以及从配置文件读取的minPasswordLength)注入进来。
  3. 移除手动实例化代码:删除@BeforeEach中手动new的逻辑,直接使用Spring注入的PasswordService实例。

修改后的测试代码

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class PasswordServiceIT {

    @Autowired
    private PasswordService passwordService;

    @Test
    public void when_generatePassword_should_generate_valid_password() {
        String password = passwordService.generatePassword();
        System.out.println(String.format("Password is: %s", password));
        // 可补充密码有效性校验:检查长度、字符类型是否符合规则等
    }
}

关键补充说明

确保BCryptPasswordEncoder、PasswordGenerator、CharacterCharacteristicsRule都已通过@Bean注解(在配置类中)定义为Spring容器中的Bean,示例配置如下:

@Configuration
public class PasswordConfig {

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public PasswordGenerator passwordGenerator() {
        // 返回真实的PasswordGenerator实现(如Apache Commons Lang的生成器)
        return new org.apache.commons.lang3.RandomStringGenerator.Builder()
                .build();
    }

    @Bean
    public CharacterCharacteristicsRule passwordCharacteristicsRule() {
        CharacterCharacteristicsRule rule = new CharacterCharacteristicsRule();
        // 添加具体的密码规则(如至少1个大写字母、1个数字等)
        return rule;
    }
}

若需临时覆盖配置文件中的密码长度参数,可在测试类上添加:

@TestPropertySource(properties = "myapp.users.passwords.min-length=10")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 23:58:13