【问题标题】:spring controller doesn't find templates in controller test弹簧控制器在控制器测试中找不到模板
【发布时间】:2025-12-14 15:20:22
【问题描述】:

我正在使用 spring-boot-starter-web、spring-boot-starter-test 和 spring-boot-starter-groovy-templates (1.2.0.M1)。

我正在尝试使用 Spring Boot 构建一个小型应用程序。我用 mockito 为 mvc 控制器编写了测试。如果我使用 maven 运行这些测试,每个控制器测试都会出现以下错误:

Servlet Could not resolve view with name 'persons/list'

我不确定我是否配置了错误。

测试用例中的错误消失了:

  • 如果我将 spring-boot-starter-parent 的版本更改为 1.1.7.RELEASE
  • 如果我使用组件扫描并将服务 bean 初始化为完整 bean

我已经设置了一个示例项目,在该项目上会出现与我的应用程序中相同的错误: https://github.com/waldemar-schneider/spring-boot-mvc-test

我错过了什么?提前致谢

【问题讨论】:

  • 如果您有可重现的测试用例,请在 GitHub 上提交针对 Spring Boot 的错误。

标签: java spring spring-mvc spring-boot spring-test


【解决方案1】:

您没有在 PersonControllerTest 使用的配置中启用自动配置,这意味着 Spring Boot 对其 Groovy 模板支持的自动配置不会发生。要解决此问题,请将 @EnableAutoConfiguration 添加到 ControllerTestConfig

它也不能真正与 1.1.7.RELEASE 一起使用,但它以不同的方式失败,您的测试没有发现。

如果你更新你的测试也调用MockMvcResultHandlers.print():

mockMvc.perform(get("/persons/"));
    .andDo(print())
    .andExpect(status().isOk())
    .andExpect(view().name("persons/list"))
    .andExpect(model().attribute("persons", hasSize(1)));

您将在输出中看到响应的正文为空:

…
MockHttpServletResponse:
          Status = 200
   Error message = null
         Headers = {Content-Type=[text/html;charset=UTF-8]}
    Content type = text/html;charset=UTF-8
            Body = 
   Forwarded URL = null
  Redirected URL = null
         Cookies = []

如果您如上所述添加@EnableAutoConfiguration,则响应将包含预期的 HTML:

…
MockHttpServletResponse:
          Status = 200
   Error message = null
         Headers = {Content-Type=[text/html;charset=UTF-8]}
    Content type = text/html;charset=UTF-8
            Body = <!DOCTYPE html><html class='no-js' lang='en'><head></head><body><h2>Person list</h2><table><thead><tr><th>Name</th><th>Surname</th></tr></thead><tr><td/><td/></tr></table></body></html>
   Forwarded URL = null
  Redirected URL = null
         Cookies = []

【讨论】:

  • 感谢您的提示。我没看到。但是我不想使用@EnableAutoConfiguration,因为我不想仅仅为了mvc控制器的单元测试而初始化整个jpa堆栈。我从 groovy 标记模板视图解析器中查看了初始化,并找到了一个可行的解决方案。我从 Spring Boot 导入了两个配置类。有兴趣的可以在 github 仓库中查看结果。
【解决方案2】:
  1. 您的application.properties 为空
  2. 什么代表'persons/list'jsp 文件? tiles 视图名称?你需要配置application.properties
  3. 考虑这样的事情

【讨论】:

  • application.properties 文件仅在您使用@EnableAutoConfiguration 时才相关。正如我在另一条评论中提到的,我不想初始化整个 jpa 堆栈(和其他功能)只是为了运行 mvc 控制器的单元测试。我想我在问题中没有详细描述我的问题,对此感到抱歉。但感谢您的想法
  • 我明白,但只是好奇如果你添加@EnableAutoConfiguration 会出现什么问题,一旦你完成了所有绿色测试,你就需要在生产环境中工作......我说的对吗?
最近更新 更多