您将如何实现,以便每个Test类将输出记录到单独的文件中? [英] How would you implement so each Test class logs output to a separate file?

查看:117
本文介绍了您将如何实现,以便每个Test类将输出记录到单独的文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果要将测试过程中收集的一些信息记录到文件中,并使用Java和TestNG或JUnit,并让每个测试类(例如 TestClass1.class )保留单独的输出以类命名的文件,如下所示:

Using Java, with either TestNG or JUnit, if you wanted to log some information gathered during a test to a file, and have each test class (such as TestClass1.class) keep a separate output file named after the class like so:

TestClass1.log

您将如何实施这种事情?我知道log4j可以将类名记录在单个文件中的每行"输出中,但是我希望每个类的输出都在单独的文件中.另外,log4j可以根据程序包名称将输出记录到不同的文件中.这些解决方案都不是我想要的,因为我希望数百个测试来创建数百个日志文件.

How would you implement this kind of thing? I know log4j can log the class name in a 'per line' of output in a single file but I want outputs for each class to be in separate files. Also, log4j can log output to different files based on package name. Neither of those solutions is what I am looking for because I want hundreds of tests to create hundreds of log files.

推荐答案

使用Log4J 1.x,您将必须手动实例化每个类中的Logger,并使用套件名称的组合为每个测试提供唯一的文件名.和类名(假设每个套件都有唯一的名称).

Using Log4J 1.x, you would have to manually instantiate the Logger in each class, providing a unique file name for each test using a combination of the suite name and class name (assuming each suite has a unique name).

例如,在测试类的setUp()方法中,定义日志文件的名称:

For example in the setUp() method of the test class, define the name of the log file:

String logFilename = context.getSuite().getName() + "_" + this.getClass().getSimpleName();

然后在测试使用的每个类中,手动实例化记录器并提供要使用的日志文件的名称:

Then in each class used by the test, manually instantiate the logger and provide the name of the log file you want to use:

public class SomeClass {
  private Logger log = null;

  public SomeClass(String logFilename) {
    log = Logger.getLogger(logFilename);
  }

但是这种解决方案不是很好,它需要将文件名传递给测试中使用的所有类.

But this solution is not very elegant, it requires to pass the file name to all the classes used in the test.

更好的解决方案:

如果可以升级到Log4J 2,它支持使用ThreadContext写入单独的日志文件: http://logging.apache.org/log4j/2.x/faq .html#separate_log_files

If you can upgrade to Log4J 2, it supports writing to separate log files using a ThreadContext: http://logging.apache.org/log4j/2.x/faq.html#separate_log_files

我还发现了此博客文章,建议使用LOGBack及其映射的诊断上下文:

I also found this blog post that suggests using LOGBack and its Mapped Diagnostic Context: http://www.nullin.com/2010/07/28/logging-tests-to-separate-files/

这篇关于您将如何实现,以便每个Test类将输出记录到单独的文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆