如何在test中写入expect_error,以便在目录中没有文件时抛出错误?

如何在test中写入expect_error,以便在目录中没有文件时抛出错误?,r,unit-testing,testing,testthat,R,Unit Testing,Testing,Testthat,我正在运行一个R代码,使用testthat在目录中没有文件时抛出一个错误。我的测试代码如下(我根据Waldi的答案进行了编辑) 我的职能是 LoadData = function(inputPath) { if(!file.exists(inputPath){ stop(paste0("There's no file at ", inputPath)) } } 我的测试代码因此消息而失败 Error: `LoadData(inputPath = filePath)`

我正在运行一个R代码,使用testthat在目录中没有文件时抛出一个错误。我的测试代码如下(我根据Waldi的答案进行了编辑)

我的职能是

LoadData = function(inputPath) {
if(!file.exists(inputPath){
 stop(paste0("There's no file at ", inputPath))
   }
}
我的测试代码因此消息而失败

Error: `LoadData(inputPath = filePath)` threw an error with unexpected message.
Expected match: "There's no file at ./UnitTest/Data/Expected_Output_2"
Actual message: "cannot open the connection"
In addition: Warning message:
In open.connection(con, "rb") :
  cannot open file './UnitTest/Data/Expected_Output_2': Permission denied

您只需准确测试预期的错误消息:

库(testthat)
LoadData=函数(inputPath){
if(长度(list.files(inputPath))==0){
停止(粘贴0(“输入路径”处没有文件))
}
}
测试(desc=“测试‘加载数据’条件1”,
代码={
filePath=“./UnitTest/Data/Expected\u Output2”
expect\u错误(LoadData(inputPath=filePath),“在./UnitTest/Data/Expected\u Output2没有文件”)
}
)
由(v0.3.0)于2020-07-06创建

由于以下原因,上述测试成功:

    LoadData("./UnitTest/Data/Expected_Output2")
出现以下错误:

Error in LoadData("./UnitTest/Data/Expected_Output2") : 
  There's no file at ./UnitTest/Data/Expected_Output2

解决此问题的一种方法是分配一个json文件,该文件实际上不存在于目录中,如下所示:

test_that(desc = "Test for 'LoadData' Condition 1",
          code = {
            filePath = "./UnitTest/Data/Expected_Output2/nofiles.json"
            expect_error(LoadData(inputPath = filePath),"There's no file at ./UnitTest/Data/Expected_Output2/nofiles.json")
          }
)

在这里,我们需要小心地理解,前面我们只是分配了一条空路径。但是我们需要分配一个实际上不存在的假设文件。这对我有用。我的测试成功。

为什么不测试“没有文件在”,因为错误就是这么说的呢?现在我得到一个类似这样的错误``错误:
LoadData(filePath)
抛出了一个带有意外消息的错误。预期匹配:“在:filepath处没有文件”实际消息:“缺少参数\“inputPath\”,没有默认值“``”。我不理解您收到的错误消息,因为filepath是作为LoadData的inputPath参数提供的。您是否完全运行了我提供的示例?是的,我也这样做了。我现在使用Reprex生成/编辑了上面的代码,因此我100%确定它不会在我的系统上引发错误。你能把它复制到一个新的脚本中并让它运行吗?如果您仍然有错误,则可能与操作系统有关:您在哪个系统上工作?我使用了您的同一段代码。它现在又给了我一个错误。我认为这与操作系统有关。
test_that(desc = "Test for 'LoadData' Condition 1",
          code = {
            filePath = "./UnitTest/Data/Expected_Output2/nofiles.json"
            expect_error(LoadData(inputPath = filePath),"There's no file at ./UnitTest/Data/Expected_Output2/nofiles.json")
          }
)