【问题标题】:Analog of TestNG Reporter.getOutput() in SpockSpock 中 TestNG Reporter.getOutput() 的模拟
【发布时间】:2020-05-21 08:14:14
【问题描述】:

我使用 Groovy 和 Spock 运行 API 测试。 由第三方库生成的请求/响应数据出现在系统中(我在 Jenkins 日志中看到)。

问题: 将每次测试迭代的系统输出记录到某个字符串列表的正确方法是什么?

TestNG 有 Reporter.getOutput(result) ,它返回所有日志条目,在测试迭代运行时出现。 Spock有类似的东西吗?

我是否正确假设它应该是Run listener 的一些实现,我开始在beforeIteration() 中记录并将其附加到afterIteration() 中的报告?

【问题讨论】:

  • 也许我误解了,因为您只使用散文,而我看不到示例代码和/或示例日志。但听起来你正在把一件简单的事情复杂化。要么让您的测试获取一个记录器并将其用于输出,或者,如果被测应用程序直接记录到 stdOut/stdErr,只需通过System.setOut() 将它们重新路由到模拟,并检查您在其上的交互,如果您想测试某些东西是记录。我不得不推测,因为像这里的许多用户一样,您没有提供MCVE,错误地认为您的解释足够清楚。
  • 请见谅。你是对的,应用程序直接记录到System.out,所以我使用了Output Stream 的实现,它同时记录了初始out 和我的copy 流对象。 copybeforeIteration() 中被清除,并附加到 RunListener 中 afterIteration() 的报告中,因此每个测试接收器都有自己的输出部分。
  • 这是否意味着您已经解决了自己的问题,或者您需要更多帮助?如果您解决了问题,最好在此处的答案中更详细地描述您的解决方案,以使每个人都受益。这样,您可以 (a) 接受您自己的解决方案以结束问题,并 (b) 向您寻求帮助的社区返回一些内容。 :-)

标签: testing logging automated-tests spock


【解决方案1】:

使用OutputCapture 解决了 spring-boot-starter-test

RunListener 示例:

class RunListener extends AbstractRunListener {

    OutputCapture outputCapture

    void beforeSpec(SpecInfo spec) {
        Helper.log "[BEFORE SPEC]: ${spec.name}"
        outputCapture = new OutputCapture()
        outputCapture.captureOutput() //register a copy off system.out, system.err streams
    }

    void beforeFeature(FeatureInfo feature) {
        Helper.log "[BEFORE FEATURE]: ${feature.name}", 2
    }

    void beforeIteration(IterationInfo iteration) {
        outputCapture.reset() //clear the stream copy before each test iteration 
    }

    void afterIteration(IterationInfo iteration) {
    }

    void error(ErrorInfo error) {
        //attach the content of copy stream object to the report if  test iteration failed
        Allure.addAttachment("${error.method.iteration.name}_console_out", "text/html", outputCapture.toString(), "txt") 

    }

    void afterFeature(FeatureInfo feature) {
    }

    void afterSpec(SpecInfo spec) {
        outputCapture.releaseOutput()
    }
}

很快:

CaptureOutput 是输出流的一个实现,它同时登录初始输出和复制流对象。该副本在beforeIteration() 中被清除,并附加到RunListenerafterIteration() 的报告中,因此每个测试都会收到自己的输出部分。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 1970-01-01
    • 2022-06-11
    • 2018-02-08
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    相关资源
    最近更新 更多