How to use R's testthat to unit test individual files?
Asked Answered
D

1

7

I'm just now getting into unit testing with R and finding it tough sledding so far. What I'd like to do is go into the R console, type test() and have testthat run tests for all the files in my R package.

Here's my environment:

sessionInfo()
R version 3.2.3 (2015-12-10)
Platform: x86_64-apple-darwin15.2.0 (64-bit)
Running under: OS X 10.11.4 (El Capitan)

And directory structure:

math
-- R
------ math.R
------ add.R 
------ subtract.R
-- tests
------ testthat.R 
------ testthat
---------- test_add.R
---------- test_subtract.R
---------- test_math.R

With the following samples of relevant files:

math.R

source('add.R')
source('subtract.R')

doubleAdd <- function(x){
    return(add(x,x) + add(x,x))
}

add.R

add <- function(a,b){
    return(a + b)
}

testthat.R

library(testthat)
library(math)

test_check("math")

test_add.R

context('add tests')

test_that('1 + 1 = 2', {
    expect_equal(2, add(1,1))
})

The Error:

In the R console, I get the following result:

library(devtools)
test()
<b>Loading math
Loading required package: testthat
Error in file(filename, "r", encoding = encoding) (from math.R#1) : 
  cannot open the connection
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
  cannot open file 'add.R': No such file or directory
</b>

However, if I switch the working directory by setwd('R') and run math.R, doubleAdd functions just fine. Also, if I delete math.R or move math.R out of the 'R' directory, test() works just fine.

How am I supposed to setup these files to have test() run tests for all my R files?

Deste answered 25/3, 2016 at 18:26 Comment(0)
G
4

If you are building a package you shouldn't be using source. You simply export your functions in the NAMESPACE file or use roxygen to do it for you. You are likely getting the error because it is looking for add.R in whatever your working directory is.

Here is a run through starting from scratch for me with basic package setup.

add.R - in R/ directory

#' @export
add <- function(a,b){
  return(a + b)
}

test_add.R - in tests/testthat/ directory

context('add tests')

test_that('1 + 1 = 2', {
  expect_equal(2, add(1,1))
})

Run in console

library(devtools)
# setup testing framework
use_testthat()

# update NAMESPACE and other docs
document()

# run tests
test()

Loading math
Loading required package: testthat
Testing math
add tests : .

DONE 

Note - you actually don't even need to export add. If it is an internal function you are testing it will still work. Just stop using source in your package.

Gabrielegabriell answered 25/3, 2016 at 18:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.