【问题标题】:Per test separated stdout/stderr for JUnit test suite on JenkinsJenkins 上 JUnit 测试套件的每个测试分隔 stdout/stderr
【发布时间】:2018-06-06 12:44:13
【问题描述】:

如何指示 JUnit(通过 Ant)在测试套件中为每个测试捕获 sdout 和 stderr?这甚至可能吗?

假设我有一个简单的 Ant 任务,它运行一套详细的 JUnit 测试。

<target name="integration-tests" depends="init">
    <property name="test.reports" value="${build.dir}/test-reports" />
    <mkdir dir="${test.reports}" />
    <junit showoutput="true" printsummary="yes" fork="yes">
        <formatter type="xml" />
        <classpath>
            <pathelement path="${run.test.classpath}" />
        </classpath>
        <test name="org.example.IntegrationTestsTestSuite" todir="${test.reports}" />
    </junit>
</target>

当 CI(在我的例子中是 Jenkins)调用这个目标时,JUnit 会生成一个整洁的 XML 文件供 CI 进一步处理(发布)。不幸的是,所有的 stdout 和 stderr 都合并为两个 XML 元素的值。

<?xml version="1.0" encoding="UTF-8" ?>
<testsuite errors="0" failures="0" hostname="foo-host" name="org.example.IntegrationTestsTestSuite" skipped="0" tests="3" time="0.115" timestamp="2018-06-06T11:45:45">
  <properties>
    <!-- all properties used by Ant build script here -->
  </properties>
  <testcase classname="org.example.integration.tests.CommonStuff" name="testSomeFooDoingAThing" time="0.088" />
  <testcase classname="org.example.integration.tests.CommonStuff" name="testOtherFooDoingAThing" time="0.023" />
  <testcase classname="org.example.integration.tests.CommonStuff" name="testAnotherFooDoingAThing" time="0.004" />
  <system-out><![CDATA[]]></system-out>
  <system-err><![CDATA[]]></system-err>
</testsuite>

如果某个测试出现问题,CI 会立即显示整个详细输出,即使是成功的测试(查看单个失败的测试时)也是如此,从而违背了此类输出的预期目的。

在我们的 IDE (Netbeans) 中运行测试时也存在同样的问题。但我记得在其他项目中,至少 IntelliJ 能够在每个测试中显示如此详细的输出(但不确定它是否适用于测试套件)。 IntelliJ 是在做其他事情来发布/预处理输出还是这是 JUnit 功能?

【问题讨论】:

  • IntelliJ 捕获 std(out/err) 流并将它们拆分为单独的文本字段,它对您几乎没有帮助。看看 JUnit 的“@Rule”和“@BeforeClass”注解。
  • @MikhailKholodkov,你在这里的意思是,如果需要这样的东西,它需要由测试本身来处理。也许使用TestWatcher,使其将std保存到文件中,然后以某种方式将此文件链接到特定的测试用例?甚至可能以编程方式生成测试报告。

标签: java jenkins junit ant


【解决方案1】:

JUnit 似乎没有内置的方式通过 Ant 执行此操作。我最终自己实现了这个功能。

根据@Mikhail 的建议,我查看了@Rule 注释,它引导我进入JUnit 的TestWatcher 类。它可用于以编程方式处理测试报告(它是单个测试方法状态事件的观察者,如“开始”、“失败”、“完成”等)。

不幸的是,@Rule 注释不能轻松应用于整个测试套件,因为它旨在用于出现测试方法的地方。我必须在每个包含测试用例的类中实现custom Suite and Runner 并伪造@Rule 的存在(通过Runner 实现中的RunRules)。

在那之后,我简单地看了一下JUnit XML report 的结构,收集了所有需要的测试统计数据并使用TestWatcher 输出(在测试方法启动时简单地调用System.setOut()System.setErr(),然后在测试后恢复它们完成)并自己编写报告文件。

Ant 任务不再需要&lt;formatter&gt; 元素,因为它只需要调用现在隐式处理的套件定义。然而,我确实使用&lt;sysproperty&gt; 将目录名称传递给自定义套件,因此它知道通过System.getProperty(String) 将结果文件存储在哪里。

使用 JUnit 4.12 版完全可以做到这一点。

【讨论】:

  • 你不会碰巧在某个地方有代码 sn-ps 或 repo,对吗?
  • @wufufufu,很遗憾没有,但是如果你按照上面的链接,你会得到所有需要的 sn-ps,除了 XML 写入部分。
猜你喜欢
  • 1970-01-01
  • 2017-08-26
  • 2017-03-28
  • 1970-01-01
  • 1970-01-01
  • 2010-10-02
  • 1970-01-01
  • 2022-08-20
  • 2020-12-23
相关资源
最近更新 更多