21

我正在使用testthatR 中的包,并且正在尝试测试文件中定义的函数example.R。该文件包含一个调用source("../utilities/utilities.R")whereutilities.R是一个文件,其中包含我编写的函数。但是,当我尝试从 测试函数时example.R,在测试脚本中获取它会出现以下错误:

Error in file(filename, "r", encoding = encoding) : 
  cannot open the connection
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
  cannot open file '../utilities/utilities.R': No such file or directory

您能否说明如何对来自另一个文件的文件中的函数运行测试?

4

3 回答 3

12

可能有点晚了,但我找到了解决方案。Test_that 将保存测试文件的目录设置为当前工作目录。请参阅 test-files.r 中的以下代码。这会导致工作目录为 /tests。因此,您的主要脚本需要 source ("../file.R"),它适用于测试,但不适用于运行您的应用程序。

https://github.com/hadley/testthat/blob/master/R/test-files.r

source_dir <- function(path, pattern = "\\.[rR]$", env = test_env(),
                       chdir = TRUE) {
  files <- normalizePath(sort(dir(path, pattern, full.names = TRUE)))
  if (chdir) {
    old <- setwd(path)
    on.exit(setwd(old))
  }

我找到的解决方案是在我的测试文件中添加 setwd("..") 并简单地获取不带路径的文件名。源(“file.R”)而不是源(“../file.R”)。似乎对我有用。

于 2015-01-14T17:23:53.707 回答
5

testthat 允许您定义和获取帮助文件(请参阅 参考资料?source_test_helpers):

辅助脚本是伴随测试脚本的 R 脚本,但前缀为helper. 这些脚本在测试运行之前运行一次。

所以对我来说完美的工作就是简单地将一个文件“helper-functions.R”包含我想要在“/tests/testthat/”中获取的代码。您不必调用source_test_helpers()自己,testthat 会在您运行测试时自动调用(例如,通过devtools::test()testthat::test_dir())。

于 2018-08-16T10:54:44.843 回答
0

我发现这个问题没有很好的解决方案,到目前为止,我一直是使用 package 在每个测试中设置工作目录here

test_that('working directory is set',{
  setwd(here())
  # test code here
})
于 2020-10-28T21:26:59.610 回答