Unit testing

Unit testing using R

  1. Create function
Fibonacci <- function(n){
    a <- 0
    b <- 1
    for (i in 1:n){
        temp <- b
        b <- a
        a <- a + temp
    }
    return(a)
}

# save as /path/to/fibo.R"

2 . Create test script

library(testthat) 

test_that("Test Fibo(15)",{
  phi <- (1 + sqrt(5))/2
  psi <- (1 - sqrt(5))/2
  expect_equal(Fibonacci(15), (phi**15 - psi**15)/sqrt(5))
})
  1. Create Run test-scripts script
library(testthat) 
source("/path/to/fibo.R")
test_results <- test_dir("/path/to/tests", reporter="summary")
test_results