Thursday 15 March 2012

java - How to do a JUnit assert on a message in a logger -


I have some code-under-test, which calls a Java logger to report its status. In the JUnit test code, I would like to verify that the correct log entry was made in this logger. Some with the following lines:

  Method precedence (Boolean x) {if (x) logger.info ("x happened")} @ test tester () // // perhaps setting up logger first MethodUnderTest (true); AssertXXXXXX (loggedLevel (), Level.INFO); }  

I think this can be done with a specially customized logger (or handler, or format), but I like to reuse a solution already existing I do (And, honestly, it is not clear to me how to obtain logarrecord from logger, but suppose it is possible.)

I also need to do this many times, I have put a small sample below, which you want to adjust to your needs. Actually, you make your own append < / Code> and add the logger you want. If you want to collect everything, the root logger is a good place to start, but you can use more specific if you wish. Do not forget to remove the appenders when you do, otherwise you can also create a memory leak. Below I did this in the test, but can be set up or @ first and tear or @after Better location based on your needs

In addition, the implementation below collects everything in the list in memory if you are logging a lot then you can leave the boring entries or in a temporary file on the disk You can consider adding a filter to the log (sign: logging event is serializable , so you can serial the event object, if your log message is.)

  import org.apache.log4j.AppenderSkeleton; Import org.apache.log4j.Level; Import org.apache.log4j.Logger; Import org.apache.log4j.spi.LoggingEvent; Import org.junit.Test; Import java.util.ArrayList; Import java.util.list; Static org.hamcrest.CoreMatchers.is import; Import static org.junit.assert.assertThat; Public Class MyTest {@Test Public Zero Test () {Final TestAppender Appenders = New Test Adapter (); Last logger logger = logger .getRootLogger (); Logger.addAppender (appender); Try {Logger.getLogger (MyTest.class). Info ("Test"); } Finally {logger.removeAppender}; } Final list & lt; Logging event & gt; Log = apder.getlag (); Last logging event firstLogEntry = log.get (0); AssertThat (firstLogEntry.getLevel (), is (level.info)); AssertThat ((string) firstLogEntry.getMessage (), is ("Test")); AssertThat (firstLogEntry.getLoggerName), is ("MyTest")); }} Class Test Appender Apparel Skeleton {Private Final List & lt; Logging event & gt; Log = new arreelist & lt; Logging event & gt; (); Layout override public boolean () {return false; } @overराइड संरक्षित शून्य अपेंड (last logging event logging event) {log.ed (logging event); } @ Override Public Wide Close () {} Public List & lt; Logging event & gt; GetLog () {new ArrayList & lt; LoggingEvent & gt; (Log); }}  

No comments:

Post a Comment