如何在测试中添加日志消息(spring boot)?

13 浏览
0 Comments

如何在测试中添加日志消息(spring boot)?

我想在我的项目中添加日志记录(用于控制台),以在Spring Boot中进行测试。\n这是我的测试代码:\n

@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");
    }
}

\n这是我的测试配置:\n

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

\n我在`test/resource`目录下创建了一个`application.properties`文件。Gradle将我的资源文件夹视为测试资源。\n这是我的`application.properties`内容:\nlogging.level.= INFO\nlogging.level.tests.= INFO\nlogging.level.org.hibernate= INFO\nlogging.level.org.springframework= INFO\nlogging.level.org.apache.cxf= INFO\n\n但是当我运行我的测试时,控制台输出为:\n

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

\n为什么会有`DEBUG`级别的输出?我只设置了`\'INFO\'`(logging.level.= INFO)。如何将其设置为只输出`\'INFO\'`级别的日志?

0
0 Comments

问题的出现原因:

在MyTest类中使用的是@RunWith(SpringJUnit4ClassRunner.class)而不是@RunWith(SpringRunner.class)

解决方法:

在MyTest类中将@RunWith(SpringJUnit4ClassRunner.class)改为@RunWith(SpringRunner.class)

参考文档:

http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-testing-spring-boot-applications

引用文档内容:

一个Spring Boot应用只是一个Spring ApplicationContext,所以测试它不需要做任何特殊的事情,只需要像测试普通的Spring上下文一样即可。不过需要注意的是,默认情况下,如果你使用SpringApplication来创建上下文,Spring Boot的外部属性、日志记录和其他功能才会被安装在上下文中。

0
0 Comments

问题的原因是在测试(Spring Boot)中如何添加日志消息。解决方法是首先将spring-boot-starter-test添加为测试依赖项,然后告诉JUnit使用刚添加依赖项的ContextLoader。更改原来的代码,将loader = SpringApplicationContextLoader.class添加到(classes = {TestConfig.class})中。

SpringApplicationContextLoader是在第一步中添加的spring-boot-starter-test中的上下文加载器,它执行通常由ApplicationBootstrapper完成的初始化操作。

根据您使用的spring-boot版本,还有其他一些可能性(例如,使用SpringBootContextLoader替代SpringApplicationContextLoader)。您可以在这个spring博客中了解更多信息:https://spring.io/blog/2016/04/15/testing-improvements-in-spring-boot-1-4

在v1.4中,SpringApplicationContextLoader已被弃用,推荐使用注释测试类,或者在必要时使用SpringBootContextLoader。在我的情况下,用于引用beans.xml文件,用于引用application.properties文件,其中我设置了日志级别。新的日志级别只在测试类启动后生效。在此之前,您仍将获得DEBUG级别的日志记录。

我使用(loader = AnnotationConfigContextLoader.class),默认情况下非常嘈杂,以DEBUG模式运行。而SpringBootContextLoader能够正确地执行任务(尽管在引导过程中,它仍然会打印出几条内部DEBUG消息,直到从application.yaml中配置日志记录)。感谢分享!

0