How to verify that error was logged with unit tests

こ雲淡風輕ζ 提交于 2019-12-31 03:44:28

问题


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:


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);
    }
}


来源:https://stackoverflow.com/questions/33049895/how-to-verify-that-error-was-logged-with-unit-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!