簡體   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