Search code examples
runit-testingtestingtestthat

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


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

Solution

  • 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.