I'm running a R code using testthat to throw an error if there is no file in the directory. My test code is as follows, (I have edited according to Waldi's answer)
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")
}
)
My function is,
LoadData = function(inputPath) {
if(!file.exists(inputPath){
stop(paste0("There's no file at ", inputPath))
}
}
My test code fails with this message,
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
You just have to test exactly the expected error message:
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")
}
)
Created on 2020-07-06 by the reprex package (v0.3.0)
The above test succeeded because the result of:
LoadData("./UnitTest/Data/Expected_Output2")
is following error:
Error in LoadData("./UnitTest/Data/Expected_Output2") :
There's no file at ./UnitTest/Data/Expected_Output2
One way to fix this was to assign a json file which actually doesn't exist in the directory like this:
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")
}
)
Here we need to be careful to understand that earlier we were just assigning a path which was empty. But we need to assign a hypothetical file which actually doesn't exist. This worked for me. My test succeed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.