如何使用R的testthat生成jUnit文件

8

我有一段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_reportertest_dir调用包装起来,但这没有什么作用。

2个回答

7

2019年更新:

testthat的2.1.0版本不再需要context以正常工作。因此,我希望您原来代码中的问题现在能够正确地解决。

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

原始答案:

4天前有testthat提交的更新涉及到这个功能。在testthat开发版本中引入了一个新选项。

如果运行:

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

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

但问题在于它可能无法使用您想要的报告器。如果安装了testthat的devtools版本:

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

出现了关于xml2的错误。尝试使用xml2的dev分支未能解决问题。考虑到这项更改是比较近期的,可能值得在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)
})

然后重新运行:

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

这对我很有帮助!由于没有包含上下文标头,会引起问题。虽然这可能是设计问题。


你也可以关注这个线程 - detroyejr

3

使用test_dir("tests/", reporter = "junit")解决方案将结果打印到testthat.Rout。我们可以使用sink()将其写入其他文件,但这只是一种变通方法。

更好的方法是直接调用JunitReporter对象并指定参数以指定报告放置位置:

library(testthat)
library(packageToTest)

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接