我正在寻找有才华的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...
})
这是@hadley打算使用的方式吗? journal article并不清楚。 我是否也应该在我的测试文件中复制库调用?您是否需要在每个上下文中设置库,或者只需要在文件开头设置库?
在r中过度调用库(包)是否可以?
使用test_dir()
和其他功能设置文件的最佳方式。我在我的函数中使用require(),但我也在上下文中设置了测试数据示例。 (在上面的例子中,您将看到我需要用于test.dt的data.table包以在其他测试中使用)。
感谢您的帮助。
答案 0 :(得分:4)
一些建议/意见:
test_file
自行运行,无需额外设置。这样,如果您只关注较大项目的一小部分,则可以在开发时轻松运行单个文件(如果运行所有测试都很慢,则非常有用)library
几乎没有惩罚,因为该函数首先检查包是否已经附加test_file
运行,则test_dir
可以正常运行而无需执行任何其他操作library(testthat)
在任何测试文件中,因为您可能正在使用test_file
或test_dir
运行它们,这需要testthat
此外,您可以查看Hadley最近的一个套餐,看看他是如何做到的(例如 dplyr
tests )。
答案 1 :(得分:0)
如果您使用devtools::test(filter="mytestfile")
,那么devtools将负责为您调用帮助文件等。通过这种方式,您无需执行任何特殊操作即可使测试文件自行运行。基本上,这与您运行测试时相同,但test_mytestfile.R
文件夹中只有testthat
。