相关疑难解决方法(0)

如何使用junit测试log4j是否记录了警告?

我正在测试一个方法,当出现问题时记录警告并返回null.
就像是:

private static final Logger log = Logger.getLogger(Clazz.class.getName());
....
if (file == null || !file.exists()) {
  // if File not found
  log.warn("File not found: "+file.toString());
} else if (!file.canWrite()) {
  // if file is read only
  log.warn("File is read-only: "+file.toString());
} else {
  // all checks passed, can return an working file.
  return file;
}
return null;
Run Code Online (Sandbox Code Playgroud)

我想测试junit是否发出了警告,除了返回null之外,在所有情况下(例如找不到文件,文件是只读的).
有任何想法吗?
谢谢,asaf :-)


UPDATE

我对Aaron的回答的实现(加上彼得的评论):

public class UnitTest {
...

@BeforeClass
public static void setUpOnce() {
  appenders = new Vector<Appender>(2);
  // …
Run Code Online (Sandbox Code Playgroud)

java logging junit unit-testing log4j

47
推荐指数
4
解决办法
5万
查看次数

标签 统计

java ×1

junit ×1

log4j ×1

logging ×1

unit-testing ×1