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

SpringBootTest注解配置属性读取为null,Maven测试执行断言失败

问题排查及解决方法

你遇到的@Value注入属性为null的问题,通常由以下几个原因导致,按优先级排查即可:

1. 缺少Spring Boot启动类(最常见原因)

@SpringBootTest注解默认会扫描当前测试类所在包及其子包下标注了@SpringBootApplication的启动类,找不到启动类时Spring上下文不会完成完整初始化,依赖注入逻辑不会生效,foo属性自然为null。

解决方法:

在测试类所在的org.xyz.mytest包下新增启动类:

package org.xyz.mytest;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }
}

2. JUnit版本和Spring Boot Test依赖不匹配

你代码中使用的是JUnit 5的org.junit.jupiter.api.Test注解,需要确保pom.xml中测试依赖配置正确,没有同时引入JUnit 4导致冲突。

正确依赖配置参考:

<dependencies>
    <!-- Spring Boot测试基础依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <!-- 排除旧版JUnit 4避免冲突 -->
        <exclusions>
            <exclusion>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <!-- JUnit 5运行引擎 -->
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

3. 低版本Spring Boot适配

如果你使用的是Spring Boot 2.2以下的旧版本,需要主动给测试类添加Spring测试扩展注解:

import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.junit.jupiter.api.extension.ExtendWith;

@ExtendWith(SpringExtension.class)
@SpringBootTest(properties = "foo=bar")
public class ConcreteTest {
    // 原有代码不变
}

附加优化建议

Assertions.assertEquals的标准参数顺序是预期值在前,实际值在后,你当前的写法是反过来的,虽然不影响本次测试的运行结果,但报错时的提示信息会逻辑颠倒,建议调整为:

Assertions.assertEquals("bar", foo);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 12:45:01