【问题标题】:Test coverage of print functions in R packageR包中打印功能的测试覆盖率
【发布时间】:2017-11-26 23:09:00
【问题描述】:

我在 R 包中有一个简单的打印功能:

print.tabyl <- function(x){
  print.data.frame(x, row.names = FALSE)
}

我正在尝试实现我的包的完整测试覆盖率,但让我很恼火的是我未经测试的打印功能将我的测试覆盖率降低到 99%(否则会是 100%)。

但我不知道如何捕获打印函数的输出以便为其编写测试。如何为打印功能编写测试?

【问题讨论】:

  • 你见过testthat包中的expect_output()函数吗?我在我的存储库中使用它来测试绘图输出:expect_output(print.tabyl(your_object))
  • 或将其包装在capture.output 中,然后返回打印行的字符串

标签: r code-coverage testthat


【解决方案1】:

根据@alistaire 的建议,我使用capture.output 编写了一个测试:

test_that("print.tabyl prints without row numbers", {
  expect_equal(
    mtcars %>% tabyl(am, cyl) %>% capture.output(),
    c(" am 4 6  8", "  0 3 4 12", "  1 8 3  2")
  )
})

这捕获了row.names 丢失;这个结果与capture.output(print.data.frame(mtcars %&gt;% tabyl(am, cyl))) 不同,后者仍然有行号。

使用capture.output 测试函数并计入codecov.io 跟踪的覆盖范围。

【讨论】:

    猜你喜欢
    • 2011-08-02
    • 2017-10-09
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多