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?
java logging unit-testing junit slf4j
Richard
source share