I’ve been introduced to unit testing while working with colleagues on quite a big project for which
we use Python.
At first I was a bit skeptical about the need of writing unit tests, but now I must admit that I
am seduced by the idea and by the huge time savings it allows. Naturally, I was wondering if the
same could be achieved with R, and was quite happy to find out that it also possible to write unit
tests in R using a package called testthat
.
Unit tests (Not to be confused with unit root tests for time series) are small functions that test
your code and help you make sure everything is alright. I’m going to show how the testthat
packages works with a very trivial example, that might not do justice to the idea of
unit testing. But you’ll hopefully see why writing unit tests is not a waste of your time,
especially if your project gets very complex (if you’re writing a package for example).
First, you’ll need to download and install testthat
. Some dependencies will also be installed.
Now, you’ll need a function to test. Let’s suppose you’ve written a function that returns the
nth Fibonacci number:
Fibonacci
You then save this function in a file, let’s call it fibo.R
. What you’ll probably do once you’ve
written this function, is to try it out:
Fibonacci(5)
## [1] 5
You’ll see that the function returns the right result and continue programming. The idea behind
unit testing is write a bunch of functions that you can run after you make changes to your code,
just to check that everything is still running as it should.
Let’s create a script called test_fibo.R
and write the following code in it:
test_that("Test Fibo(15)",{
phi
The code above uses Binet’s formula, a closed form formula that gives the nth Fibonacci number and compares it
our implementation of the algorithm. If you didn’t …read more
Source:: r-bloggers.com