rtestthatcovr

Testthat and covr in one go


I would like to run tests for a package with testthat and compute code coverage with covr. Furthermore, the results from testthat should be saved in the JUnit XML format and the results from covr should be saved in the Cobertura format.

The following code does the trick (when getwd() is the root of the package):

options("testthat.output_file" = "test-results.xml")
devtools::test(reporter = testthat::JunitReporter$new())

cov <- covr::package_coverage()
covr::to_cobertura(cov, "coverage.xml")

However, the tests are executed twice. Once with devtools::test and once with covr::package_coverage.

My understanding is that covr::package_coverage executes the tests, but it does not produce test-results.xml.

As the title suggests, I would like get both test-results.xml and coverage.xml with a single execution of the test suite.


Solution

  • From the covr reference manual (https://cran.r-project.org/web/packages/covr/covr.pdf)

    This function uses tools::testInstalledPackage() to run the code, if you would like to test your package in another way you can set type = "none" and pass the code to run as a character vector to the code parameter

    covr::package_coverage(
        type = "none",
        code = "testthat::test_package(
    'myPackage',
    reporter = testthat::JunitReporter$new(file = 'test-results.xml')
    )")