logging.level.org.springframework: ERROR
29 July 2014
The Spring Framework provides a nice JUnit integration, which allows one to write integration-style tests that make use of a fully loaded and configured Spring context.
This is great help when writing an integration test suite to test something like a database, as you do not need to manually create all the code required to interact
with the database. Instead, you can rely upon Spring to configure the beans just as it would at runtime. Recently, I found myself in a situation where I needed to
write just such an integration test, though this time for an application that uses Spring Boot. You do not need to do anything special to leverage the JUnit integration
integration, as that is provided by the Spring Test module of the Spring Framework
project. What you do not get by default, is all of the auto-configuration magic that Spring Boot provides, including logging configuration. With the release of Spring Boot
1.1.4, it is now possible to add the following to your application.properties
or application.yml
configuration file to control the logging output:
logging.level.org.springframework: ERROR
Additionally, I wanted to be able to turn on SQL logging when executing my integration tests via the Spring Boot JPA configuration:
spring.jpa.properties.hibernate.show_sql: true
However, simply using the JUnit integration does not cause Spring Boot to load the configuration or perform any of the auto-configuration that it does when running the application.
To enable Spring Boot to work its magic when running unit/integration tests that load a context, the first step is to include the spring-boot-starter-test
dependency:
testCompile 'org.springframework.boot:spring-boot-starter-test:1.1.4.RELEASE'
The presence of this dependency will cause Spring Boot to perform all the normal start-up auto-configuration that occurs when running the application. However, in order for this to
actually happen, you need to tell JUnit to use the SpringApplicationContextLoader
when loading the context:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={TestConfiguration.class}, loader = SpringApplicationContextLoader.class)
public class DatabaseIntegrationTests {
...
}
When the Spring Framework loads the test configuration, it does so via Spring Boot's SpringApplicationContextLoader
, which is provided by the spring-boot-starter-test
. This
context loader supports all of the auto-configuration magic that we know and love in Spring Boot. Now, you can adjust logging levels, provide configuration and have your contexts
make use of the Spring Boot auto-configuration annotations as part of your test suite!