首页 > 解决方案 > Spock 中 TestNG Reporter.getOutput() 的模拟

问题描述

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

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

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

我是否正确假设它应该是运行监听器的一些实现,我开始录制beforeIteration()并将其附加到afterIteration()中的报告?

标签: testingloggingautomated-testsspock

解决方案


通过使用 spring-boot-starter-test中的OutputCapture解决

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()并附加到 中的报告中afterIteration()RunListener因此每个测试都会收到自己的输出部分。


推荐阅读