我正在寻找最好的实践帮助与辉煌的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...
})
test_dir()
和其他功能,最好的方法是设置文件。我在我的函数中使用require(),但我也在上下文中设置了测试数据示例。 (在上面的例子中,您将看到我需要用于test.dt的data.table包以在其他测试中使用)。谢谢你的帮助。
一些建议/意见:
test_file
自行运行,无需额外设置。这样,如果您只关注较大项目的一小部分,则可以在开发时轻松运行单个文件(如果运行所有测试的速度很慢,则非常有用)library
几乎没有什么惩罚,因为该函数首先检查包是否已经附加test_file
运行,那么test_dir
将工作正常,而无需做任何额外的事情library(testthat)
,因为可能是您使用test_file
或test_dir
运行它们,这需要加载testthat
另外,你可以看看Hadley最近的一个包装,看看他是如何做到的(例如dplyr
tests)。
如果您使用devtools::test(filter="mytestfile")
,那么devtools将负责为您调用帮助文件等。通过这种方式,您无需执行任何特殊操作即可使测试文件自行运行。基本上,这与运行测试时相同,但在test_mytestfile.R
文件夹中只有testthat
。