Junit Log Verification Reports

I have a java 8 application with class foo:

import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Foo { private final Logger log = LoggerFactory.getLogger(Foo.class); public String something() { log.info("doing foo test"); return "test"; } } 

I am writing a JUnit test case (Junit 4.11):

 public class FooTest { private Foo foo; @Before public void setUp() throws Exception { foo = new Foo(); } @Test public void testSomething() { String result = foo.something(); assertEquals(result,"test"); } } 

My task is to write a test case that checks the something method so that it returns the value AND the logging operator to make sure that something is being written to the log. I spent several hours searching the web to figure out how to configure junit to check the logging instructions. I tried this , this , this and this method to no avail.

I don’t know, I’m doing something wrong or what. But here my code is based on the last example:

 public class FooTest { private Foo foo; @Mock private Appender appender; @Captor private ArgumentCaptor captor; @Before public void setUp() throws Exception { foo = new Foo(); MockitoAnnotations.initMocks(this); Logger.getRootLogger().addAppender(appender); } @After public void tearDown() throws Exception { Logger.getRootLogger().removeAllAppenders(); } @Test public void testSomething() { String result = foo.something(); assertEquals(result,"test"); verify(appender).doAppend(((LoggingEvent) captor.capture())); LoggingEvent loggingEvent = (LoggingEvent) captor.getValue(); assertEquals(loggingEvent.getRenderedMessage(), "doing foo test"); } } 

But when I run this, I get the following error:

 Wanted but not invoked: appender.doAppend(<Capturing argument>); -> at <package>.testSomething(FooTest.java:22) Actually, there were zero interactions with this mock. 

Is there an easier way to accomplish what I want? If this is the best way, then what am I doing wrong?

+7
java logging unit-testing junit slf4j
source share
1 answer

Of course!

  • Create Your Own Custom Singleton Appender
  • Change the configuration of the test registrar to enter this extension in addition to all the other registrations you will perform.
  • clear() during each @Begin test
  • assert-test is usually until testing is complete.

In fact, SLF4J already has an implementation that you can look at.

+6
source share

All Articles