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

9
我们使用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;
    }
}

然而,关于如何使用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>

版本:

        <junit.jupiter.version>5.3.1</junit.jupiter.version>
        <mockito.version>2.23.0</mockito.version>

并创建了一个测试类:

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();
        }
    }

}

当我在调试模式下运行时,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)}

但这只是为了背景,首先我想让它在简单的样例项目中运行,然后再考虑让它在我们复杂的项目中运行。

2个回答

3
您不能直接将emailConfigBean注入为freemarker.template.ConfigurationFreeMarkerConfigurationFactoryBean是一个工厂Bean。要获取Confuguration,您需要调用factorybean.getObject()。
因此,不要写成:
    @Autowired
    @Qualifier("emailConfigBean")
    private Configuration emailConfig;

只需自动装配您的工厂bean FreeMarkerConfigurationFactoryBean,并使用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();
        }

GitHub上进行测试。


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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
    <version>1.5.6.RELEASE</version>
</dependency>

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

然后,您可以通过自动装配freemarkerConfig(或使用构造函数注入)来使用它:

    @Autowired
    private Configuration freemarkerConfig;

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接