[英]mocking Logger.getLogger() using jmock
I am working on legacy code and writing some junit tests (I know, wrong order, never mind) using jmock (also wasn't my choice, nothing I can change about that) and I have class which does some elaborate logging, messing with Strings in general. 我正在研究遗留代码,并使用jmock编写了一些junit测试(我知道,顺序错误,没关系)(这不是我的选择,我对此无能为力),并且我有一个类进行一些详细的日志记录,弄乱了字符串一般。 We are using log4j for logging and I want to test those logged messages. 我们正在使用log4j进行日志记录,我想测试那些记录的消息。 I thought about mocking Logger class, but I don't know how to do it. 我曾考虑过模拟Logger类,但我不知道该怎么做。
As usually we have Logger done like this: 通常,我们的Logger是这样完成的:
private static final Logger LOG = Logger.getLogger(SomeClass.class);
Does anyone have any idea how to mock method .getLogger(class) or any other idea how to check what exactly has been logged? 有谁知道如何模拟方法.getLogger(class)或任何其他想法如何检查已记录的内容?
If you really think you need to do this, then you need to take a look at PowerMock . 如果您确实认为需要执行此操作,则需要看一下PowerMock 。 More specifically, it's ability to mock static methods . 更具体地说,它具有模拟静态方法的能力。 PowerMock integrates with EasyMock and Mockito, but some hunting about might result in you finding a JMock integration too if you have to stick with that. PowerMock与EasyMock和Mockito集成在一起,但是如果您不得不坚持的话,可能还会发现一些JMock集成问题。
Having said that, I think that setting up your test framework so that it logs nicely without affecting your tests, and ensuring your tests do not depend upon what gets logged is a better approach. 话虽如此,我认为设置测试框架以使其在不影响测试的情况下很好地记录日志, 并确保测试不依赖于记录的日志是一种更好的方法。 I once had to maintain some unit tests that checked what had been logged, and they were the most brittle and useless unit tests I have ever seen. 我曾经不得不维护一些单元测试来检查记录的内容,它们是我见过的最脆弱,最无用的单元测试。 I rewrote them as soon as I had the time available to do it. 我一有空就重写了它们。
Check this similar question: How to mock with static methods? 检查这个类似的问题: 如何使用静态方法进行模拟?
And by the way, it is easier to search for an existing qusetion to your problem than to post a question and wait for answers. 顺便说一句,搜索现有的问题要比发布问题并等待答案要容易得多。
The easiest way I have found is using the mock log4j objects in JMockit. 我发现的最简单方法是在JMockit中使用模拟log4j对象。
You just need to the add the annotation 您只需要添加注释
@UsingMocksAndStubs(Log4jMocks.class)
to your test class and all code touched by the tester class will be using a mock Logger object. 到您的测试类,并且测试者类涉及的所有代码都将使用模拟Logger对象。
But this wont log the messages. 但这不会记录消息。 You can get away from the hassle of dealing with static objects with this. 这样您就可以摆脱处理静态对象的麻烦。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.