繁体   English   中英

如果目录中没有文件,如何在 testthat 中编写 expect_error 以引发错误?

[英]how to write expect_error in testthat to throw an error if there is no file in the directory?

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

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

我的 function 是,

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

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

library(testthat)


LoadData = function(inputPath) {
  if(length(list.files(inputPath))==0){
    stop(paste0("There's no file at ", inputPath))
  }
}


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

reprex package (v0.3.0) 于 2020 年 7 月 6 日创建

上述测试成功的原因是:

    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")
          }
)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM