【问题标题】:Unit Testing Freemarker templates in SpringBoot - unable to initialize freemarker configurationSpringBoot中的单元测试Freemarker模板 - 无法初始化freemarker配置
【发布时间】:2019-12-06 20:54:27
【问题描述】:

我们正在使用 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)}

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

【问题讨论】:

    标签: spring-boot junit freemarker junit5


    【解决方案1】:

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

    所以而不是

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

    只需自动装配您的 factorybean 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;
    

    【讨论】:

      猜你喜欢
      • 2013-10-01
      • 2012-05-16
      • 2018-06-28
      • 1970-01-01
      • 2014-05-21
      • 2011-07-28
      • 1970-01-01
      • 2011-10-11
      • 1970-01-01
      相关资源
      最近更新 更多