Pages

Wednesday, February 10, 2010

How to check logs in Junit Tests

Now the software development methodology has been changed in terms of testing.Earlier testing was done by QA team at the end of development.Even though there was a role for unit testing ,it was like developer will take his own measure to make sure the code is working . With the evolution of Junit , a good framework for standardized unit testing was in place.Frameworks like Spring gives importance to unit testing.
What can we test in a unit test? In order to test a call flow , we were in need of checking the log files.usually the junit test spits the logs in to the console. how can we search for a particular string in the console log? We were using log4j for logging in the application. The options we were considering was,
1. Can we inject log to the class using dependency injection so that in the test we can inject a mock log which will write to a file .This file will contain logs generated by this test hence will be easier to handle and faster search.
2. Can we any way access the log instance of the class we are testing so that we can direct it to a file.
At the end, with the bits and pieces of Internet help we were able to achieve this in a simpler and smarter way.
----------------------------------------------------------------------------------------
Sample code for org.apache.log4j.Logger

protected static Logger logger = Logger.getLogger(yourclass.class.getName());
private static ByteArrayOutputStream out = new ByteArrayOutputStream();
private static WriterAppender writerAppender = new WriterAppender(new PatternLayout(), out);
logger.addAppender(writerAppender);
--Execute the acion which will generate the log--
String logMsg = out.toString();
assertNotNull(logMsg);
assertTrue("Error", logMsg.contains("your string"));
out.flush();
out.close();
logger.removeAppender(writerAppender);


---------------------------------------------------------------------------------------------
If you are using jdk logging API then instaed of appender ,there is something called 'handler' which will give you the same benefit.

Sample code For java.util.logging.Logger

Logger logger = Logger.getLogger(YourClass.class.getName());
Formatter formatter = new SimpleFormatter();
ByteArrayOutputStream out = new ByteArrayOutputStream();
Handler handler = new StreamHandler(out, formatter);
logger.addHandler(handler);
--Execute the acion which will generate the log--
handler.flush();
String logMsg = out.toString();
assertNotNull(logMsg);
assertTrue(logMsg.contains("your string"));
logger.removeHandler(handler);
---------------------------------------------------------------------------------
Feel free to post your comments or queries
Related Posts Plugin for WordPress, Blogger...