如何使用 R testthat 生成 jUnit fie

How to produce jUnit fie with R testthat

我有 R 代码(不是包),我想使用 testthat 进行验收测试,并在 Jenkins 中使用输出。

我可以从两个演示代码结构的文件开始:

# -- test.R
source("test-mulitplication.R")

# -- test-mulitplication.R
library(testthat)
test_that("Multipilation works ", {
  res <- 5 * 2
  expect_equal(res, 10)
})

在 运行 之后,我想获得一个 xml 文件,其中包含每个测试文件的结果或单个文件中的所有测试。

我注意到 testthat 中有一个 reporter 功能,但其中大部分似乎是包内部的。目前尚不清楚如何保存测试结果以及功能的灵活性。

遗憾的是,该部分的文档不完整。

编辑

我现在找到了一种使用更好的语法和 junit 输出选项来测试目录的方法:

# -- tests/accpetance-tests.R
options(testthat.junit.output_file = "test-out.xml")
test_dir("tests/")

# -- tests/test-mulitplication.R
library(testthat)
test_that("Multipilation works ", {
  res <- 5 * 2
  expect_equal(res, 10)
})

我相信这会在报告器中生成一个 XML 对象,但我仍然不知道如何将它保存到文件中。

我尝试用 with_reporter 包装 test_dir 调用,但效果不大。

2019 年更新:

testthat 的 2.1.0 版不再需要 context 才能正常工作。因此,我希望您的原始代码中的问题能够正常工作。

来源:https://www.tidyverse.org/articles/2019/04/testthat-2-1-0/

原答案:

testthat commit 4 days ago 引用了此功能。 testthat 的开发版本中引入了一个新选项。

如果你运行:

devtools::install_github("r-lib/testthat")
options(testthat.output_file = "test-out.xml")
test_dir("tests/")

这应该会在您的工作目录中生成一个文件。

问题是它可能不适用于您想要的记者。安装了测试的 devtools 版本:

options(testthat.output_file = "test-out.xml")
test_dir("tests/", reporter = "junit")

产生有关 xml2 的错误。尝试 xml2 的 dev 分支并没有解决问题。鉴于此更改是最近发生的,因此可能值得 filing an issue over on github.

不确定这是否能让您更接近,但我们正在收到一份输出报告,这是一个开始!

编辑

这有效,但您需要确定并在测试的顶部添加一个 "context",否则您会收到错误消息。尝试将乘法测试的顶部更改为:

# -- test-mulitplication.R
library(testthat)
context("Testing Succeeded!")
test_that("Multipilation works ", {
  res <- 5 * 2
  expect_equal(res, 10)
})

context("Test Failed!")
test_that("Multipilation works ", {
  res <- 5 * 2
  expect_equal(res, 12)
})

然后 re-run:

options(testthat.output_file = "test-out.xml")
test_dir("tests/", reporter = "junit")

对我有用!由于某些原因,不包括上下文 header 会导致问题。这可能是设计使然。

带有 test_dir("tests/", reporter = "junit") 的解决方案在结果 testthat.Rout 中打印出来。我们可以使用 sink() 将其写入其他文件,但这是一种解决方法。

更好的方法是直接调用JunitReporter对象并指定参数放在哪里:

library(testthat)
library(packageToTest)

test_check("packageToTest", reporter = JunitReporter$new(file = "junit_result.xml"))