0

I'm using SLF4J and my class has a logger like this:

private static final Logger logger = LoggerFactory.getLogger(MyClass.class);

I'm writing a unit test. When an error occurs, it should be logged in a certain way. I'd like to write a test that looks like this:

@Test
public void loggedCorrectMessage() {
    //setup that would generate an exception

    MyClass myClass = new MyClass();
    myClass.myMethod();

    //somehow get the slf4j logger
    expect(slfLogger.getErrorMessages()).toContain("The error I was looking for.");
}

I don't know how to get that SLF4J logger unless I turn it from private to public and mock it out with dependency injection. A lot of my teammates don't like when I do that. Is there a way I can get access to this logger and check how it's been used in the above unit test?

It might be worth mentioning I'm using the spring framework, but my logger isn't a @Bean.

Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
  • Considering your rep, I find it amazing that you didn't find any answers with a web search, e.g. [`slf4j test logger`](https://www.google.com/search?q=slf4j+test+logger), i.e. a web search for a SLF4J logger specifically used for testing. – Andreas Sep 07 '18 at 20:22
  • For your specific case, you can use reflection to rip out the psf field if you must. – Kevin Caravaggio Sep 07 '18 at 21:22

0 Answers0