SpringBoot中的单元测试Freemarker模板-无法初始化Freemarker配置 [英] Unit Testing Freemarker templates in SpringBoot - unable to initialize freemarker configuration

查看:109
本文介绍了SpringBoot中的单元测试Freemarker模板-无法初始化Freemarker配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

we are using Freemarker for generating the HTML code for the emails our application is going to be sending.

我们的使用和配置基于 https://github.com/hdineth /SpringBoot-freemaker-电子邮件发送 特别是:

Our usage and configuration is based off of https://github.com/hdineth/SpringBoot-freemaker-email-send Particularly:

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运行单元测试,绝对没有任何信息或文档.

However, there is absolutely no information or documentation anywhere, about how to run Unit Tests for this using 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为空. 这是为什么?

When I run that in debug mode, emailConfig is null. Why is that?

他们的测试示例

Their test example https://github.com/hdineth/SpringBoot-freemaker-email-send/blob/master/src/test/java/com/example/techmagister/sendingemail/SendingemailApplicationTests.java works if I add the same autowired property, but it is a full SprintBoot context that is slow to boot, and I need to test just template usage, without actually sending out the email.

在我们的实际代码(大型,多模块项目)中,我还有另一个错误org.springframework.beans.factory.UnsatisfiedDependencyException 造成原因:

In our actual code (which is large, multi module project), I have another error org.springframework.beans.factory.UnsatisfiedDependencyException caused by:

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

但这只是出于上下文考虑,首先,我想使其在简单的示例项目中运行,然后担心使其在我们的复杂项目中运行.

But that is just for context, first I want to get it working in the simple, sample project then worry about getting it working in our complex one.

推荐答案

您不能直接将emailConfigBean自动接线为freemarker.template.Configuration FreeMarkerConfigurationFactoryBean是factorybean. 要获取Confuguration,您需要调用factorybean.getObject()

You cannot autowire your emailConfigBean directly as a freemarker.template.Configuration FreeMarkerConfigurationFactoryBean is a factorybean. To get the Confuguration you need to call factorybean.getObject()

所以而不是

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

只需自动连接factorybean FreeMarkerConfigurationFactoryBean并使用emailConfig.getObject().getTemplate("email.ftl")

just autowire your factorybean FreeMarkerConfigurationFactoryBean and load your template with 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的配置:

On the other hand... In a Spring Boot application the Freemarker configuration can be simplified by using the spring-boot-starter-freemarker dependency:

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

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

This starter for building MVC web applications using FreeMarker views adds the necessary auto-configuration. All you need to do is placing your template files in the resources/templates folder.

然后您可以自动连接freemarkerConfig(或使用构造函数注入):

Then you just can autowire the freemarkerConfig (or use constructor injection):

    @Autowired
    private Configuration freemarkerConfig;

这篇关于SpringBoot中的单元测试Freemarker模板-无法初始化Freemarker配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆