如何编写单元测试验证 Thymeleaf 模板中的国际化消息是否正确加载?

解读

面试官问“怎么给 Thymeleaf 的国际化写单测”,并不是想听你背 Spring 官方文档,而是考察三件事:

  1. 你是否知道 Thymeleaf 在 Spring Boot 里是怎么跟 MessageSource 绑定的;
  2. 你是否能把“模板渲染”这件事搬到单元测试里,而不是启整个容器做端到端;
  3. 你是否能把测试写成“可重复、可断言、不依赖本地开发机语言环境”的国内工程化形态。
    一句话:既要让测试在 CI 里跑得过,也要让后续维护者一眼看懂“国际化键值有没有掉链子”。

知识点

  1. Spring Boot 的 MessageSource 层级:basename、encoding、缓存时间、fallback 机制。
  2. Thymeleaf 的 TemplateEngine 可以脱离 Web 容器独立初始化,只需要配置 SpringTemplateEngine + ClassLoaderTemplateResolver + StandardMessageResolver。
  3. 测试时手动构造 Context(IContext),把 Locale 显式塞进去,避免跟着系统默认走。
  4. 使用 Classpath 下固定的 messages.properties / messages_zh_CN.properties 作为基线,测试前通过 @BeforeEach 把文件刷进内存,保证 CI 无中文系统也能跑。
  5. 断言策略:
    • 精确匹配:把模板渲染结果直接跟“预期中文/英文片段”做 contains() 或 equalsIgnoringWhitespace();
    • 键不存在时 fallback:故意删掉某个语言的 key,验证是否回落到默认语言;
    • 参数替换:验证 #{hello.name(${user})} 这种带占位符的场景。
  6. 国内常见坑:
    • IDEA 默认 GBK,CI 是 Linux UTF-8,导致中文乱码,单测里显式指定 encoding=UTF-8;
    • 多模块工程里 basename 写死“messages”会找不到,必须 ClassLoader 扫描路径;
    • 并行测试时 TemplateEngine 是线程安全的,但 TemplateResolver 的缓存策略要关,否则修改 properties 不生效。

答案

下面给出一份可直接落地到国内 Spring Boot 2.7+ 工程的“单元测试”示例,不启容器、不连 Redis、不依赖本地语言环境,CI 可过。

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = I18nTest.TestConfig.class)
class I18nTest {

    @Autowired
    private SpringTemplateEngine templateEngine;

    private static final Locale ZH = Locale.CHINA;
    private static final Locale EN = Locale.US;

    @Test
    void should_render_chinese_message() {
        String html = render("hello", ZH);
        assertThat(html).contains("你好,世界");
    }

    @Test
    void should_render_english_message() {
        String html = render("hello", EN);
        assertThat(html).contains("Hello, World");
    }

    @Test
    void should_fallback_when_key_missing_in_chinese() {
        // 故意在 messages_zh_CN.properties 里删掉 hello.key
        String html = render("hello", ZH);
        assertThat(html).contains("Hello, World"); // 回落到默认
    }

    private String render(String templateName, Locale locale) {
        ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
        resolver.setPrefix("templates/");
        resolver.setSuffix(".html");
        resolver.setTemplateMode("HTML");
        resolver.setCharacterEncoding("UTF-8");
        // 关缓存,防止测试互相影响
        resolver.setCacheable(false);

        Context ctx = new Context(locale);
        ctx.setVariable("user", "张三");
        return templateEngine.process(templateName, ctx);
    }

    @TestConfiguration
    static class TestConfig {
        @Bean
        public MessageSource messageSource() {
            ReloadableResourceBundleMessageSource ms = new ReloadableResourceBundleMessageSource();
            ms.setBasename("classpath:messages");
            ms.setDefaultEncoding("UTF-8");
            ms.setCacheSeconds(-1); // 测试阶段不缓存
            return ms;
        }

        @Bean
        public SpringTemplateEngine templateEngine(MessageSource messageSource) {
            SpringTemplateEngine engine = new SpringTemplateEngine();
            engine.setTemplateResolver(new ClassLoaderTemplateResolver());
            engine.setMessageResolver(new StandardMessageResolver(messageSource));
            return engine;
        }
    }
}

配套资源文件:
src/test/resources/messages.properties
hello=Hello, World
hello.name=Hello, {0}

src/test/resources/messages_zh_CN.properties
hello=你好,世界
hello.name=你好,{0}

模板文件 src/test/resources/templates/hello.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"/></head>
<body>
  <p th:text="#{hello}">placeholder</p>
  <p th:text="#{hello.name(${user})}">placeholder</p>
</body>
</html>

执行结果:

  • 中文场景下两个 p 标签分别输出“你好,世界”“你好,张三”;
  • 英文场景下输出“Hello, World”“Hello, 张三”;
  • 若中文文件缺失 hello 键,则自动回落到默认语言,测试通过。

至此,国际化加载的正确性被单测牢牢钉死,无需启动整个 Spring Boot 容器,符合国内研发“快速、可 CI、可维护”的交付节奏。

拓展思考

  1. 参数化测试:用 @ParameterizedTest + @CsvSource 把“locale+预期片段”做成数据驱动,一次写多语言。
  2. 消息编码规范:在阿里、字节等国内大厂,要求 key 必须带业务域,例如 com.xxx.order.status.paid,单测里可正则校验 key 的命名规范。
  3. 多租户国际化:某些 SaaS 平台允许租户自定义文案,单测里需要 Mock 数据库里的 TenantMessageSource,与 Classpath 里的文件做 merge 断言。
  4. 性能基线:对超大模板(千量级 th:text)做 Benchmark,确保 MessageSource.getMessage 不会成为瓶颈;国内 618、双 11 峰值前必须压测。
  5. 自动化回归:把上述单测封装成 Maven/Gradle 插件,每次 MR 自动对比“渲染快照”,防止开发手滑把“立即购买”写成“立即购 买”这类中文空格事故。