rrunit

RUnit: could not find function "checkEquals"


I am creating an R package with the standard directory hierarchy. Inside the R directory, I create a test subdirectory.

In the R directory, I create a uTest.R file containing:

uTest <- function() {
  test.suite <- defineTestSuite('test',
                               dirs = file.path('R/test'))
  test.result <- runTestSuite(test.suite)
  printTextProtocol(test.result)
}

In the R/test directory, I create a runit.test.R file containing:

test.validDim <- function() {
  testFile <- "test/mat.csv"

  generateDummyData(testFile,
                    10,
                    10)

  checkEquals(validDim(testFile), TRUE)
}

I build and install my package using R CMD INSTALL --no-multiarch --with-keep.source RMixtComp in Rstudio. When I try to launch the function uTest(), I get this error message:

1 Test Suite : 
test - 1 test function, 1 error, 0 failures
ERROR in test.validDim: Error in func() : could not find function "checkEquals"

However, if I call library(RUnit) prior to calling uTest(), everything works fine. In the import field of the DESCRIPTION file, I added RUnit, and in the NAMESPACE file I added import(RUnit).

How can I call uTest() directly after loading my package, without manually loading RUnit ?


Solution

  • You should not add RUnit to the Depends (or Imports) field in the DESCRIPTION file (despite the comment to the contrary). Doing so implies that the RUnit package is necessary in order to use your package, which is likely not the case. In other words, putting RUnit in Depends or Imports implies RUnit needs to be installed (Imports) and on the users' search path (Depends) in order for them to use your package.

    You should add RUnit to the Suggests field in the DESCRIPTION file, then modify your uTest function as below:

    uTest <- function() {
      stopifnot(requireNamespace("RUnit"))
    
      test.suite <- RUnit::defineTestSuite('test', dirs = file.path('R/test'))
      test.result <- RUnit::runTestSuite(test.suite)
      RUnit::printTextProtocol(test.result)
    }
    

    Doing this allows you to use RUnit for your tests, but does not require users to have RUnit installed (and possibly on their search path) in order to use your package. Obviously, they'll need RUnit if they wish to run your tests.