Edheene
Edheene

Reputation: 455

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. We are using log4j for logging and I want to test those logged messages. I thought about mocking Logger class, but I don't know how to do it.

As usually we have Logger done like this:

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?

Upvotes: 2

Views: 1687

Answers (4)

n3o
n3o

Reputation: 2873

The easiest way I have found is using the mock log4j objects in JMockit.

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.

See this

But this wont log the messages. You can get away from the hassle of dealing with static objects with this.

Upvotes: 0

Jon
Jon

Reputation: 3602

If you really think you need to do this, then you need to take a look at 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.

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.

Upvotes: 3

adranale
adranale

Reputation: 2874

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.

Upvotes: 0

Andrzej Jozwik
Andrzej Jozwik

Reputation: 14649

You can write own appender and redirect all output to it.

Upvotes: 4

Related Questions