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

SpringBoot JUnit测试报错:找不到@SpringBootConfiguration

解决Spring Boot JUnit测试中“Unable to find a @SpringBootConfiguration”错误

问题场景

使用Maven管理依赖,运行JUnit测试(Run As -> JUnit Test)时触发以下错误:

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
    at org.springframework.util.Assert.state(Assert.java:76)
    ...(省略部分堆栈内容)

控制台输出关键日志:

08:43:37.249 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [TestSelectWord]: using SpringBootContextLoader
08:43:37.255 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [edu.uclm.esi.juegos.TestSelectWord]: no resource found for suffixes {-context.xml, Context.groovy}.
08:43:37.256 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [edu.uclm.esi.juegos.TestSelectWord]: TestSelectWord does not declare any static, non-private, non-final, nested classes annotated with @Configuration.

测试代码如下(包声明为空):

package ;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;

@SpringBootTest
@ExtendWith(SpringExtension.class)
@AutoConfigureMockMvc
public class TestSelectWord {
    
    @Autowired
    private MockMvc server;
    
    @Test
    void test1() {

    }
}

同类测试文件无需额外配置即可运行,已尝试安装Spring Boot插件,问题未解决。

解决办法

1. 修复测试类的包声明

测试代码中package ;为空是核心问题之一,Spring Boot测试默认会扫描测试类所在包及子包中的@SpringBootConfiguration(通常由@SpringBootApplication包含)。

  • 将测试类的包声明修改为与主项目启动类(带@SpringBootApplication的类)一致的父包或子包,例如主启动类在edu.uclm.esi.juegos,则测试类包应为edu.uclm.esi.juegos。

2. 显式指定配置类

如果测试类无法通过包扫描找到配置类,直接在@SpringBootTest中指定主启动类:

@SpringBootTest(classes = YourMainApplication.class) // 替换为你的主启动类名称
@AutoConfigureMockMvc
public class TestSelectWord {
    // ... 测试代码
}

注:Spring Boot 2.2+版本中@ExtendWith(SpringExtension.class)可省略,@SpringBootTest已默认集成该扩展

3. 校验主项目结构

确保项目中存在且仅有一个带@SpringBootApplication注解的主启动类,该注解包含@SpringBootConfiguration,是测试加载上下文的核心入口。

4. 确认Maven依赖完整性

检查pom.xml中是否正确引入测试依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 09:35:14