用testthat在哪里放置库调用?

时间:2015-04-10 08:41:38

标签: r testing testthat

我正在寻找有才华的testthat的最佳实践帮助。将library(xyzpackage)调用用于使用所有包功能的最佳位置在哪里?

我首先设置了runtest.R设置路径和包。 然后我运行test_files(test-code.R) 保存上下文和测试。结构示例如下:

# runtests.R
library(testthat)
library(data.table)

source("code/plotdata-fun.R")

mytestreport <- test_file("code/test-plotdata.R")

# does other stuff like append date and log test report (not shown)

并在我的测试文件中,例如test-plotdata.R(精简版):

#my tests for plotdata
context("Plot Chart")

test_that("Inputs valid", {

  test.dt  = data.table(px = c(1,2,3), py = c(1,4,9))
  test.notdt <- c(1,2,3)

  # illustrating the check for data table as first param in my code
  expect_error(PlotMyStandardChart(test.notdt, 
                                   plot.me = FALSE),
                "Argument must be data table/frame")

  # then do other tests with test.dt etc...
})
  1. 这是@hadley打算使用的方式吗? journal article并不清楚。 我是否也应该在我的测试文件中复制库调用?您是否需要在每个上下文中设置库,或者只需要在文件开头设置库?

  2. 中过度调用库(包)是否可以?

  3. 使用test_dir()和其他功能设置文件的最佳方式。我在我的函数中使用require(),但我也在上下文中设置了测试数据示例。 (在上面的例子中,您将看到我需要用于test.dt的data.table包以在其他测试中使用)。

  4. 感谢您的帮助。

2 个答案:

答案 0 :(得分:4)

一些建议/意见:

  • 设置每个文件,以便可以使用test_file自行运行,无需额外设置。这样,如果您只关注较大项目的一小部分,则可以在开发时轻松运行单个文件(如果运行所有测试都很慢,则非常有用)
  • 多次调用library几乎没有惩罚,因为该函数首先检查包是否已经附加
  • 如果您设置每个文件以便可以使用test_file运行,则test_dir可以正常运行而无需执行任何其他操作
  • 您不需要library(testthat)在任何测试文件中,因为您可能正在使用test_filetest_dir运行它们,这需要testthat

此外,您可以查看Hadley最近的一个套餐,看看他是如何做到的(例如 dplyr tests )。

答案 1 :(得分:0)

如果您使用devtools::test(filter="mytestfile"),那么devtools将负责为您调用帮助文件等。通过这种方式,您无需执行任何特殊操作即可使测试文件自行运行。基本上,这与您运行测试时相同,但test_mytestfile.R文件夹中只有testthat

相关问题