SpringBoot 中的单元测试 Freemarker 模板 - 无法初始化 freemarker 配置

Car*_*don 6 junit freemarker spring-boot junit5

我们正在使用 Freemarker 为我们的应用程序将要发送的电子邮件生成 HTML 代码。

我们的使用和配置基于https://github.com/hdineth/SpringBoot-freemaker-email-send 特别是:

package com.example.techmagister.sendingemail.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;
import org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean;

import java.io.IOException;

@Configuration
public class FreemarkerConfig {

    @Bean(name="emailConfigBean")
    public FreeMarkerConfigurationFactoryBean getFreeMarkerConfiguration(ResourceLoader resourceLoader) {
        FreeMarkerConfigurationFactoryBean bean = new FreeMarkerConfigurationFactoryBean();
        bean.setTemplateLoaderPath("classpath:/templates/");
        return bean;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,在任何地方都没有关于如何使用 JUnit 5 为此运行单元测试的信息或文档。

当我添加相关依赖项时

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${junit.jupiter.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-params</artifactId>
            <version>${junit.jupiter.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit.jupiter.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>${mockito.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-junit-jupiter</artifactId>
            <version>${mockito.version}</version>
            <scope>test</scope>
        </dependency>
Run Code Online (Sandbox Code Playgroud)

版本:

        <junit.jupiter.version>5.3.1</junit.jupiter.version>
        <mockito.version>2.23.0</mockito.version>
Run Code Online (Sandbox Code Playgroud)

并做了一个测试类:

package com.example.techmagister.sendingemail;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import java.io.IOException;


@ExtendWith({SpringExtension.class, MockitoExtension.class})
@Import(com.example.techmagister.sendingemail.config.FreemarkerConfig.class)
public class EmailTestTest {
    private static final Logger LOGGER = LogManager.getLogger(EmailTestTest.class);

    @Autowired
    @Qualifier("emailConfigBean")
    private Configuration emailConfig;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void test() throws Exception {
        try {
            Template template = emailConfig.getTemplate("email.ftl");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

当我在调试模式下运行它时,emailConfig为空。这是为什么?

如果我添加相同的自动装配属性,他们的测试示例https://github.com/hdineth/SpringBoot-freemaker-email-send/blob/master/src/test/java/com/example/techmagister/sendingemail/SendingemailApplicationTests.java工作,但它是一个完整的 SprintBoot 上下文,启动速度很慢,我只需要测试模板使用情况,而不实际发送电子邮件。

在我们的实际代码(这是一个大型的多模块项目)中,我还有一个错误org.springframework.beans.factory.UnsatisfiedDependencyException 是由以下原因引起的:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'freemarker.template.Configuration' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=emailConfigBean)}
Run Code Online (Sandbox Code Playgroud)

但这只是为了上下文,首先我想让它在简单的示例项目中工作,然后担心让它在我们的复杂项目中工作。

Dir*_*yne 3

您不能emailConfigBean直接将您的自动装配为freemarker.template.Configuration FreeMarkerConfigurationFactoryBean是一个工厂bean。要获取Confuguration您需要调用factorybean.getObject()

所以而不是

    @Autowired
    @Qualifier("emailConfigBean")
    private Configuration emailConfig;
Run Code Online (Sandbox Code Playgroud)

只需自动装配你的工厂beanFreeMarkerConfigurationFactoryBean并加载你的模板emailConfig.getObject().getTemplate("email.ftl")


    @Autowired
    @Qualifier("emailConfigBean")
    private FreeMarkerConfigurationFactoryBean emailConfig;

    @Test
    void testFreemarkerTemplate(){
        Assertions.assertNotNull(emailConfig);
        try {
            Template template =
                emailConfig
                    .getObject()               // <-- get the configuration
                    .getTemplate("email.ftl"); // <-- load the template
            Assertions.assertNotNull(template);
        } catch (Exception e) {
            e.printStackTrace();
        }

Run Code Online (Sandbox Code Playgroud)

工作测试github


另一方面......在 Spring Boot 应用程序中,可以通过使用来简化 Freemarker 配置spring-boot-starter-freemarker依赖项来简化 Freemarker 配置:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
    <version>1.5.6.RELEASE</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

这个使用 FreeMarker 视图构建 MVC Web 应用程序的入门程序添加了必要的自动配置。您所需要做的就是将模板文件放入该resources/templates文件夹中。

然后你就可以自动装配freemarkerConfig或使用构造函数注入):

    @Autowired
    private Configuration freemarkerConfig;
Run Code Online (Sandbox Code Playgroud)