use log4j in junit test assertions

I need to confirm that some error/warnings are logged in the code being tested. The logger is usually private static final that we cannot get from the junit. The following pattern would be able to achieve it.


	public void testLogMessageIsSent() {
		Logger logger = Logger.getLogger(ClassUnderTest.class);

		ByteArrayOutputStream out = new ByteArrayOutputStream();
		Layout layout = new SimpleLayout();
		Appender appender = new WriterAppender(layout, out);

		try {

			String logMsg = out.toString();

			assertThat("log message should not be null", logMsg, notNullValue());
			assertThat("Should contain warning message", logMsg, containsString(SOME_VALUE));

		} finally {


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s