2

Let's say I have the following class like this:

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

  public void myMethod(String condition) {
    if (condition.equals("terrible")) {
      LOG.error("This is terrible!");
      return; 
    }
    //rest of logic in method
  }
}

My unit test for MyClass looks something like this:

@Test
public void testTerribleCase() throws ModuleException {
  myMethod("terrible"); 
  //Log should contain "This is terrible!" or assert that error was logged
}

Is there some way to determine that the log contains the specific String "This is terrible"? Or even better, is there a way to determine if it logged an error at all without looking for a specific String value?

cvoep28
  • 423
  • 5
  • 9
  • 21
  • Generally you'd mock the log, but depending on your logging library you probably can't even do *that*. – Makoto Oct 10 '15 at 03:27
  • 2
    Possible duplicate of [How to do a junit assert on a message in a logger](http://stackoverflow.com/questions/1827677/how-to-do-a-junit-assert-on-a-message-in-a-logger) – Joe Oct 10 '15 at 03:28
  • 1
    Is there a good reason as to why you need to test this is logging out? The only time I've ever felt that it was good to test your logging was when you were logging out to a critical file. – Makoto Oct 10 '15 at 03:31
  • I want to test that logs took place because I want to ensure that the rest of the method doesn't execute if the condition is true (I have a return; statement after the log which means it should skip the rest of the method). – cvoep28 Oct 10 '15 at 03:35
  • 2
    It would be a better idea to directly verify that whatever is in "rest of logic in method" was not interacted with. – kryger Oct 10 '15 at 13:42
  • This is what I ended up doing. – cvoep28 Oct 10 '15 at 17:03

1 Answers1

3

Create a custom filter to look for the message and record if it was ever seen.

@Test
public void testTerribleCase() throws ModuleException {
    class TerribleFilter implements Filter {
        boolean seen;
        @Override
        public boolean isLoggable(LogRecord record) {
            if ("This is terrible!".equals(record.getMessage())) {
                seen = true;
            }
            return true;
        }
    }

    Logger log = Logger.getLogger(MyClass.class.getName());
    TerribleFilter tf = new TerribleFilter();
    log.setFilter(tf);
    try {
        myMethod("terrible");
        assertTrue(tf.seen);
    } finally {
        log.setFilter(null);
    }
}
jmehrens
  • 10,580
  • 1
  • 38
  • 47