为什么SpringBootTests不调用SpringBootApplication类的主方法

Iho*_* M. 3 spring-boot

我试图弄清楚为什么会这样。我的main()方法包含一些对于应用程序启动至关重要的初始化过程,而Spring Boot集成测试并未调用它。有人可以解释这种行为吗?

i.b*_*nko 5

Spring Boot测试不需要调用,SpringBootApplication.main()因为它可以自己扫描pacakes中的配置。它试图模仿使用Spring Boot框架创建上下文的过程。换句话说,它基于程序包结构进行扫描,从预定义的位置加载外部配置,可选地运行自动配置启动器等。有趣的是,如果您只是@SpringBootTest参加测试课程,扫描过程将朝上进行

示例:用于以下项目结构

??? com
    ??? example
        ??? demo
            ??? config
            ?   ??? AppConfig.java
            ??? test
            |   ??? SpringBootAppTest.java
            ??? DemoApplication.java
Run Code Online (Sandbox Code Playgroud)

Spring Boot测试将SpringBootConfiguration在以下位置搜索:

  1. com.example.demo.test
  2. com.example.demo
  3. com.example
  4. com

因此,当它找到SpringBootApplication(是SpringBootConfiguration)加载时,它是上下文,它会在示例案例中扫描其他配置和另一个方向的bean com.example.demo.configuration。因此,将加载所有上下文。

例如,如果您SpringBootAppTest向上移动com.example,它将失败(因为SpringBootApplication找不到),并显示以下错误:

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test 
Run Code Online (Sandbox Code Playgroud)