Java Spring开机测试配置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38469706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:21:28  来源:igfitidea点击:

Spring boot test configuration

javaspring-bootspring-test

提问by sansari

I have a spring boot application with main class like below:

我有一个带有如下主类的 Spring Boot 应用程序:

@SpringBootApplication
public class Application {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }
}

Now I want to test my services and created a base test class:

现在我想测试我的服务并创建了一个基础测试类:

@SpringApplicationConfiguration(Application.class)
public abstract class TestBase {
}

When I run my test I get exception:

当我运行测试时,出现异常:

Caused by: java.lang.IllegalArgumentException: Can not load an ApplicationContext with a NULL 'contextLoader'. Consider annotating your test class with @ContextConfiguration.
    at org.springframework.util.Assert.notNull(Assert.java:115)
    at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:117)
    at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:148)

Then I change my base test class using ContextConfiguration

然后我使用 ContextConfiguration 更改我的基本测试类

@ContextConfiguration(classes = Application.class)
public abstract class TestBase {
}

This time I get DataSource initialization error. I am wondering why it is failing in first case and why in second case it does not load my application.propertieswhere I have configured datasource.

这次我收到 DataSource 初始化错误。我想知道为什么它在第一种情况下失败,为什么在第二种情况下它没有加载我配置数据源的application.properties

Thank you!

谢谢!

回答by Mike3355

Something like that:

类似的东西:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class ApplicationTest{

   @Autowired
   Foo foo; //whatever you are testing

   @Test
   public void FooTest() throws Exception{
     Foo f = foo.getFooById("22");
     assertEquals("9B", f.getCode); 
   }
 //TODO look into MockMVC for testing services
}

回答by Deepak Bhatia

I faced the same issue it is because my ServletInitializer was in the different package. Problem resolved after correcting the package structure.

我遇到了同样的问题,因为我的 ServletInitializer 在不同的包中。更正包结构后问题已解决。

回答by GOXR3PLUS

Example for Testing with

测试示例

  • Spring Boot
  • Spring Boot Test Configuration
  • JUnit 5
  • FreeMarker
  • 弹簧靴
  • Spring Boot 测试配置
  • JUnit 5
  • 自由标记

You will not find all this so simple as below :) Took long time to find out .

你不会发现这一切像下面这么简单:) 花了很长时间才找到。

Configuration:

配置

@TestConfiguration
@PropertySource(value = "classpath:test.properties", encoding = "UTF-8")
public class GlobalConfig {

    @Bean(name = "JsonMapper")
    public JsonMapper jsonMapper() {

        return new JsonMapper();
    }

    @Bean(name = "ObjectMapper")
    public ObjectMapper objectMapper() {

        return new ObjectMapper();
    }

    @Bean(name = "Mapper")
    public Mapper dozer() {

        return new DozerBeanMapper();
    }

    @Bean(name = "Validator")
    public Validator validator() {

        return new DefaultValidatorAdapter();
    }

}

Actual Test File:

实际测试文件

import freemarker.template.Configuration;
import global.GlobalConfig;
import org.apache.commons.io.FileUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;


@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = {GlobalConfig.class, MessagePersistManager.class, TemplateManager.class, FileOperationsManager.class, Configuration.class})
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class MessagePersistManagerTest {

    @Autowired
    private MessagePersistManager messagePersistManager;

    @Autowired
    private TemplateManager templateManager;

    @Autowired
    private FileOperationsManager fileOperationsManager;

    @Autowired
    private Configuration freemarkerConfiguration;


    @Value("${channel.outbound.ftp.local.directory}")
    private String sepaFilesBasePath;

    @BeforeAll
    private void init() throws Exception {

        System.out.println("Creating Base Dir=" + sepaFilesBasePath);
        Files.createDirectories(Paths.get(sepaFilesBasePath));

        /* FreeMarker Configuration */
        freemarkerConfiguration.setClassForTemplateLoading(this.getClass(), "/templates/");

    }


    @AfterAll
    private void destroy() throws Exception {

        System.out.println("Deleting Base Dir=" + sepaFilesBasePath);
        FileUtils.deleteDirectory(new File(sepaFilesBasePath));

    }


    @Test
    void persistSepaFile() {
        messagePersistManager.persistSepaFile("sepaWinnings.xml", generateData());
        System.out.println("e");
        assert (true);
    }