本文介绍了如何在测试中添加日志消息(春季启动)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的项目中添加日志记录(用于控制台),以便在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");
    }
}

和我的测试配置:

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

}

我在 test/resource 中创建了一个 application.properties 文件.Gradle将我的资源文件夹视为测试资源.
这是我的 application.properties :

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

在控制台中

.为什么?
我只设置了'INFO'(logging.level.= INFO).为什么控制台中'DEBUG'?怎样才能将其设置为'INFO'?

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'?

推荐答案

这是一个两步过程.

首先,添加 spring-boot-starter-test 作为测试依赖项.然后告诉JUnit使用刚刚添加的依赖项中的 ContextLoader .

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

更改

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

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

上下文加载器位于第一步中添加的 spring-boot-starter-test 中,并且通常由 ApplicationBootstrapper 完成初始化魔术.

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

根据您使用的spring-boot版本,还有其他一些可能性(例如,使用 @SpringApplicationConfiguration 代替 @ContextConfiguration ).您可以在此春季博客中了解有关此内容的更多信息: https://spring.io/blog/2016/04/15/testing-improvements-in-spring-boot-1-4

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

这篇关于如何在测试中添加日志消息(春季启动)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 17:17