简体   繁体   English

Spring开机测试配置

[英]Spring boot test configuration

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.这次我收到 DataSource 初始化错误。 I am wondering why it is failing in first case and why in second case it does not load my application.properties where I have configured datasource.我想知道为什么它在第一种情况下失败,为什么在第二种情况下它没有加载我配置数据源的application.properties

Thank you!谢谢!

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
}

Example for Testing with测试示例

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

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

I faced the same issue it is because my ServletInitializer was in the different package.我遇到了同样的问题,因为我的 ServletInitializer 在不同的包中。 Problem resolved after correcting the package structure.更正包结构后问题已解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM