对 SLF4J 日志消息进行单元测试的最佳方法是什么? [英] What is the best way to unit-test SLF4J log messages?

查看:37
本文介绍了对 SLF4J 日志消息进行单元测试的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 slf4j,我想对我的代码进行单元测试,以确保在特定条件下生成警告/错误日志消息.我宁愿这些是严格的单元测试,所以我宁愿不必从文件中提取日志配置来测试是否生成了日志消息.我使用的模拟框架是 Mockito.

I'm using slf4j and I want to unit test my code to make sure that warn/error log messages are generated under certain conditions. I'd rather these be strict unit tests, so I'd prefer not to have to pull up logging configuration from a file in order to test that the log messages are generated. The mocking framework I'm using is Mockito.

推荐答案

我认为您可以使用自定义 appender 解决您的问题.创建一个实现 org.apache.log4j.Appender 的测试 appender,并在 log4j.properties 中设置您的 appender,并在您执行测试用例时加载它.

I think you could solve your problem with a custom appender. Create a test appender which implements the org.apache.log4j.Appender, and set your appender in the log4j.properties and load it when you execute test cases.

如果你从那个 appender 回调到测试工具,你可以检查记录的消息

If you call back to the test harness from that appender you can check the logged messages

这篇关于对 SLF4J 日志消息进行单元测试的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆