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.

 

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

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

		try {
			ClassUnderTest.methodThatLogsAMessage();

			String logMsg = out.toString();

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

		} finally {
			logger.removeAppender(appender);
		}
	}

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s