mic*_*str 7 testing r 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)
Run Code Online (Sandbox Code Playgroud)
在我的测试文件中,例如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...
})
Run Code Online (Sandbox Code Playgroud)
这是@hadley打算使用的方式吗?从期刊文章中不清楚.我是否也应该在我的测试文件中复制库调用?您是否需要在每个上下文中设置库,或者只需要在文件开头设置一个库?
可以在r中过度调用库(包)吗?
要使用test_dir()
和其他功能,最好的方法是设置文件.我在我的函数中使用require(),但我也在上下文中设置了测试数据示例.(在上面的示例中,您将看到我需要用于test.dt的data.table包以在其他测试中使用).
谢谢你的帮助.
一些建议/意见:
test_file
无需额外设置即可单独运行。这样,如果您只专注于较大项目的一小部分,则可以在开发过程中轻松运行单个文件(如果运行所有测试都很慢,则很有用)library
多次调用几乎没有什么惩罚,因为该函数首先检查包是否已附加test_file
,则test_dir
可以正常工作而无需执行任何其他操作library(testthat)
在任何测试文件中,因为大概是使用test_file
或来运行它们test_dir
,因此需要testthat
将其加载另外,您可以查看Hadley最近提供的软件包之一,以了解他的工作方式(例如dplyr
tests)。