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

SpringBoot测试ApplicationContext加载失败,无法找到指定Bean

SpringBoot测试ApplicationContext加载失败解决方案

问题核心

报错显示测试上下文无法找到UnderwriterMicroserviceApplication类型的Bean,根源在于:

  • @SpringBootTest(classes = SmokeTest.class)错误指定测试类作为配置入口,导致Spring仅加载测试类相关资源,未扫描主应用的配置与Bean
  • 测试中不必要地注入了主应用类,实际上上下文启动成功即代表应用初始化正常,无需注入该类

解决方案

1. 修正@SpringBootTest注解

将测试类的@SpringBootTest注解指定主应用类作为配置入口,或直接省略classes属性(SpringBoot会自动扫描当前包及子包下的@SpringBootApplication类):

// 方式一:显式指定主应用类
@SpringBootTest(classes = UnderwriterMicroserviceApplication.class)
// 方式二:省略classes属性,自动扫描
// @SpringBootTest

2. 移除不必要的注入

删除测试类中对UnderwriterMicroserviceApplication的注入代码,并调整断言逻辑:

// 移除以下注入代码
// @Autowired
// UnderwriterMicroserviceApplication application;

// 调整contextLoads方法断言
@Test
void contextLoads() {
    assertNotNull(rootController);
    assertNotNull(applicantController);
}

3. 统一Java版本(可选但建议)

日志显示运行环境为Java17,但pom.xml中指定的编译版本为8,可能引发兼容性问题,建议同步版本:

<properties>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
</properties>

修改后的完整SmokeTest.java

package com.aline.underwritermicroservice;

import org.springframework.boot.test.context.SpringBootTest;
import com.aline.underwritermicroservice.controller.ApplicantController;
import com.aline.underwritermicroservice.controller.RootController;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.SpringVersion;

import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

@SpringBootTest(classes = UnderwriterMicroserviceApplication.class)
class SmokeTest {

    @Autowired
    RootController rootController;

    @Autowired
    ApplicantController applicantController;

    @Test
    void contextLoads() {
        assertNotNull(rootController);
        assertNotNull(applicantController);
    }

    @Test
    void usingCorrectVersions() {
        assertNotNull(SpringVersion.getVersion());
        assertTrue(SpringVersion.getVersion().startsWith("5"));
    }

}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 22:13:11