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

Spring Boot测试加载ApplicationContext失败问题求助

Spring Boot测试加载ApplicationContext失败问题解决

问题说明

添加@TestPropertySource("/application-test.properties")和@Sql(value = {"/create-user-before.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)注解后,测试抛出java.lang.IllegalStateException: Failed to load ApplicationContext错误,移除@TestPropertySource注解后测试可正常执行。报错核心原因:

Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing table [message]

测试代码如下:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
//@TestPropertySource("/application-test.properties")
public class LoginTest {
    @Autowired
    private MessageController controller;
    @Autowired
    private MockMvc mockMvc; // MockMvc 创建MVC测试副本

    @Test
    public void contextLoads() throws Exception {
        this.mockMvc.perform(get("/")) // 请求项目主页
                .andDo(print())
                .andExpect(status().isOk()) // 预期状态码200
                .andExpect(content().string(containsString("Hello, guest")))
                .andExpect(content().string(containsString("Please, login")));
    }

    @Test// 测试用户访问权限控制
    public void accessDeniedTest() throws Exception {
        this.mockMvc.perform(get("/main"))
                .andDo(print())
                .andExpect(status().is3xxRedirection())
                .andExpect(redirectedUrl("http://localhost/login"));
    }

    @Test
//   @Sql(value = {"/create-user-before.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
    public void correctLoginTest() throws Exception {
        this.mockMvc.perform(formLogin().user("admin2").password("1")) // 验证登录凭证
                .andExpect(status().is3xxRedirection())
                .andExpect(redirectedUrl("/"));
    }

    @Test // 测试错误登录凭证
    public void badCredentials() throws Exception {
        this.mockMvc.perform(post("/login").param("username", "Alfred"))
                .andDo(print())
                .andExpect(status().isForbidden()); // 预期状态码403
    }
}

解决方案

1. 修正JPA自动建表配置

检查application-test.properties中的JPA配置,确保Hibernate能自动创建所需表结构:

# 测试环境推荐使用,每次启动自动创建表,测试结束可配置create-drop自动删除
spring.jpa.hibernate.ddl-auto=create
# 或者使用update,保留现有数据并更新表结构
# spring.jpa.hibernate.ddl-auto=update

若配置为spring.jpa.hibernate.ddl-auto=validate,Hibernate会严格校验数据库表与实体类的匹配性,缺少message表时直接报错,需改为允许自动建表的配置。

2. 补充@Sql脚本中的表创建语句

如果不想依赖Hibernate自动建表,需确保@Sql执行的脚本包含所有必要表的创建逻辑:

  • 创建create-tables-before.sql,写入message表和用户表的创建语句
  • 修改注解为:
@Sql(value = {"/create-tables-before.sql", "/create-user-before.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)

3. 使用@ActiveProfiles替代@TestPropertySource(推荐)

Spring Boot推荐通过激活测试环境配置文件的方式加载测试配置,避免路径配置问题:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test") // 自动加载classpath下的application-test.properties
public class LoginTest {
    // ... 测试代码
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 02:14:55