Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add log messages in tests (spring boot)?

I want to add logging (for console) in my project, for a test in Spring Boot. I have my test:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestConfig.class})
public class MyTest {

    private final static org.slf4j.Logger LOGGER = LoggerFactory.getLogger(MyTest.class);

    @Autowired
    public UserDao userDao;

    @Test
    public void test1() {
        LOGGER.info("info test");
        LOGGER.debug("debug test");
    }
}

and my test config:

@Configuration
@EnableJpaRepositories("example.dao")
@ComponentScan(basePackageClasses = { MyServiceImpl.class})
@EntityScan({"example.model"})
@Import({DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class TestConfig {

}

I created an application.properties file in test/resource. Gradle sees my resource folder as a resource for tests.
Here's my application.properties:

logging.level.= INFO
logging.level.tests.= INFO
logging.level.org.hibernate= INFO
logging.level.org.springframework= INFO
logging.level.org.apache.cxf= INFO

But when I run my test, I have:

16:59:17.593 [main] INFO  tests.MyTest - info test
16:59:17.594 [main] DEBUG tests.MyTest - debug test

in the console. Why?
I set just 'INFO'(logging.level.= INFO). Why is 'DEBUG' in the console? How can to set it just to'INFO'?

like image 326
Paushchyk Julia Avatar asked Jun 25 '15 14:06

Paushchyk Julia


1 Answers

It's a two step proccess.

First, add spring-boot-starter-test as a test dependency. Then tell JUnit to use the ContextLoader from the just added dependency.

Change

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestConfig.class})
public class MyTest {
    ...

to

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestConfig.class},     
                      loader = SpringApplicationContextLoader.class)
public class MyTest {
    ...

The context loader lives in spring-boot-starter-test added in the first step and does the initialization magic normally done by the ApplicationBootstrapper.

Depending on the spring-boot version you are using there are some other possibilities (e.g. using @SpringApplicationConfiguration in place of @ContextConfiguration). You can read more about that in this spring blog: https://spring.io/blog/2016/04/15/testing-improvements-in-spring-boot-1-4

like image 141
Dirk Lachowski Avatar answered Nov 13 '22 07:11

Dirk Lachowski