Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why SpringBootTests do not invoke main method of SpringBootApplication class

Tags:

spring-boot

I am trying to figure out why this is happening. My main() method contains some initialization procedures that are vital for application startup and spring boot integration tests are not invoking it. Can someone pls explain this behavior.

like image 731
Ihor M. Avatar asked Aug 17 '26 07:08

Ihor M.


1 Answers

Spring boot test does not need call SpringBootApplication.main() because it scans pacakes for configurations by himself. It tries to mimic the processes that use Spring Boot framework for creating the context. In other words it scans based on package structures, loads external configurations from predefined locations, optionally runs auto-configuration starters and so on. Interesting this is that If you just put @SpringBootTest on your test class, scanning process will be done on packages in up direction

Example: For following project structure

└── com
    └── example
        └── demo
            ├── config
            │   └── AppConfig.java
            ├── test
            |   └── SpringBootAppTest.java
            └── DemoApplication.java

Spring Boot test will search for SpringBootConfiguration in:

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

So when it will find SpringBootApplication (which is SpringBootConfiguration) it is load it's context that scan for other configuration and beans in another direction in sample case com.example.demo.configuration . Therefore all context will be loaded.

If you for example move SpringBootAppTest up to com.example it will fail (because SpringBootApplication can't be found) with following error:

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test 
like image 128
i.bondarenko Avatar answered Aug 18 '26 22:08

i.bondarenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!