[英]How to use R's testthat to unit test individual files?
我现在刚刚进入R单元测试并且发现它到目前为止很难进行滑雪橇。 我想做的是进入R控制台,键入test()
并测试我的R包中的所有文件的测试。
这是我的环境:
sessionInfo()
R version 3.2.3 (2015-12-10)
Platform: x86_64-apple-darwin15.2.0 (64-bit)
Running under: OS X 10.11.4 (El Capitan)
和目录结构:
math
-- R
------ math.R
------ add.R
------ subtract.R
-- tests
------ testthat.R
------ testthat
---------- test_add.R
---------- test_subtract.R
---------- test_math.R
以下是相关文件的示例:
math.R
source('add.R')
source('subtract.R')
doubleAdd <- function(x){
return(add(x,x) + add(x,x))
}
add.R
add <- function(a,b){
return(a + b)
}
testthat.R
library(testthat)
library(math)
test_check("math")
test_add.R
context('add tests')
test_that('1 + 1 = 2', {
expect_equal(2, add(1,1))
})
错误:
在R控制台中,我得到以下结果:
library(devtools)
test()
<b>Loading math
Loading required package: testthat
Error in file(filename, "r", encoding = encoding) (from math.R#1) :
cannot open the connection
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
cannot open file 'add.R': No such file or directory
</b>
但是,如果我通过setwd('R')
切换工作目录并运行math.R, doubleAdd
函数就好了。 另外,如果我删除math.R或将math.R移出'R'目录, test()
工作正常。
我怎么设置这些文件让test()
运行测试我的所有R文件?
如果您正在构建程序包,则不应使用source
。 您只需在NAMESPACE
文件中导出您的函数或使用roxygen为您执行此操作。 您可能会收到错误,因为它在您的工作目录中查找add.R
这是一个从头开始为我完成的基本软件包设置。
add.R - 在R /目录中
#' @export
add <- function(a,b){
return(a + b)
}
test_add.R - 在tests / testthat /目录中
context('add tests')
test_that('1 + 1 = 2', {
expect_equal(2, add(1,1))
})
在控制台中运行
library(devtools)
# setup testing framework
use_testthat()
# update NAMESPACE and other docs
document()
# run tests
test()
Loading math
Loading required package: testthat
Testing math
add tests : .
DONE
注意 - 您实际上甚至不需要导出add
。 如果它是您正在测试的内部功能,它仍然可以工作。 只需停止在包中使用source
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.