Testing Spring Boot Applications
A Spring Boot application is a Spring ApplicationContext, so nothing very special has to be done to test it beyond what you would normally do with a vanilla Spring context.
 
|  | External properties, logging, and other features of Spring Boot are installed in the context by default only if you use SpringApplicationto create it. | 
 
|  | If you are using JUnit 4, do not forget to also add @RunWith(SpringRunner.class)to your test, otherwise the annotations will be ignored.
If you are using JUnit 5, there is no need to add the equivalent@ExtendWith(SpringExtension.class)as@SpringBootTestand the other@…Testannotations are already annotated with it. | 
 
By default, @SpringBootTest will not start a server.
You can use the webEnvironment attribute of @SpringBootTest to further refine how your tests run:
 
- 
MOCK(Default) : Loads a webApplicationContextand provides a mock web environment.
 Embedded servers are not started when using this annotation.
If a web environment is not available on your classpath, this mode transparently falls back to creating a regular non-webApplicationContext.
It can be used in conjunction with@AutoConfigureMockMvcor@AutoConfigureWebTestClientfor mock-based testing of your web application.
 
- 
RANDOM_PORT: Loads aWebServerApplicationContextand provides a real web environment.
Embedded servers are started and listen on a random port.
 
- 
DEFINED_PORT: Loads aWebServerApplicationContextand provides a real web environment.
Embedded servers are started and listen on a defined port (from yourapplication.properties) or on the default port of8080.
 
- 
NONE: Loads anApplicationContextby usingSpringApplicationbut does not provide any web environment (mock or otherwise).
 
 
|  | If your test is @Transactional, it rolls back the transaction at the end of each test method by default.
However, as using this arrangement with eitherRANDOM_PORTorDEFINED_PORTimplicitly provides a real servlet environment, the HTTP client and server run in separate threads and, thus, in separate transactions.
Any transaction initiated on the server does not roll back in this case. | 
 
|  | @SpringBootTestwithwebEnvironment = WebEnvironment.RANDOM_PORTwill also start the management server on a separate random port if your application uses a different port for the management server. |