3

I use slf4j extensively in my application. For stability reasons, there are scenarios where my code will gracefully handle an error condition and simply log it as an error and move on.

However, I want to write tests that demonstrate that, for given input, my SUT does not generate any such error logs.

For example, my code often looks like this:

public class MyClass {
  private static final Logger LOG = LoggerFactory.getLogger(MyClass.class);

  // snip

  public void someMethod(DTO input) {
    try {
      // snip
    } catch (SomeException e) {
      LOG.error("Code failed here!", e);
      // recover gracefully
    }
  }
}

I want to, in my test case, catch something like

Mockito.verify(LOG.error(Mockito.anyString(), Mockito.any(SomeException.class), times(0));

However, because of the way I generate the LOG object - using the slf4j LoggerFactory api, it's difficult to mock the LOG object. What I'm really looking to do is have a different testing slf4j implementation (I use logback in production) that JUnit and Mockito have access to. How can I do this?

I am using JUnit 4.11, Mockito 1.9.5, and Jukito 1.3. I'd prefer not to use PowerMock as it's incompatible with Jukito.

durron597
  • 31,968
  • 17
  • 99
  • 158
  • mock something in the graceful recovery? – ratchet freak Feb 13 '15 at 17:00
  • static fields are evil :) especially those final. so if you don't want to be able to swap LOG, only crazy solution that comes to my mind is to make your own implementation of SLF4J and provide it instead of logback. – sodik Feb 13 '15 at 17:28
  • Can't you spy your recovery code? – fge Feb 13 '15 at 17:36
  • One solution would be to delegate the recovery code to a method which takes the exception as an argument; you would then `verify()` that the recovery method is `never()` called – fge Feb 13 '15 at 17:37
  • I believe you should be checking to make sure exception is not thrown. if you design test cases for checking log messages, it is too brittle and will break as soon as someone changes the message. – minion Feb 13 '15 at 21:29

0 Answers0