Test log4j logging – add appender to root

Great article from slackhacker.com
http://slackhacker.com/2009/12/08/testing-logging-behaviour-in-four-code-lines-flat/

http://slackhacker.com/2012/04/16/testing-logging-behaviour-sans-mockito/

 

 

@Test
	public void testException {
		String customExceptionMessage = "Junit test exception";
		StringWriter stringWriter = new StringWriter();
		Appender appenderMock = new WriterAppender(new SimpleLayout(), stringWriter);
		Logger.getRootLogger().addAppender(appenderMock);
		
		try {
			Mockito.doThrow(new RuntimeException(customExceptionMessage)).when(testClass).doTestMethod(Mockito.any());
			/* run the test class*/
		} catch (Exception ex) {
			assertThat(ex.getMessage(), Is.is(customExceptionMessage));
		} finally {
			assertThat(stringWriter.toString(), StringContains.containsString(customExceptionMessage));
		}
		
		Logger.getRootLogger().removeAppender(appenderMock);
	}
Test log4j logging – add appender to root

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 )

Connecting to %s