How to verify that error was logged with unit test

2020-04-30 02:36发布

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?

1条回答
淡お忘
2楼-- · 2020-04-30 02:44

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);
    }
}
查看更多
登录 后发表回答