Building formulae
Easy peasy STATA-like marginal effects with R
Functional peace of mind
It's lists all the way down
It's lists all the way down, part 2: We need to go deeper
Mapping a list of functions to a list of datasets with a list of columns as arguments
Teaching the tidyverse to beginners
Why I find tidyeval useful
tidyr::spread() and dplyr::rename_at() in action
Introducing brotools
Lesser known dplyr 0.7* tricks
Lesser known dplyr tricks
Lesser known purrr tricks
Make ggplot2 purrr
Functional programming and unit testing for data munging with R available on Leanpub
How to use jailbreakr
My free book has a cover!
Work on lists of datasets instead of individual datasets by using functional programming
Method of Simulated Moments with R
New website!
Nonlinear Gmm with R - Example with a logistic regression
Simulated Maximum Likelihood with R
Bootstrapping standard errors for difference-in-differences estimation with R
Careful with tryCatch
Data frame columns as arguments to dplyr functions
Export R output to a file
I've started writing a 'book': Functional programming and unit testing for data munging with R
Introduction to programming econometrics with R
Merge a list of datasets together
Object Oriented Programming with R: An example with a Cournot duopoly
R, R with Atlas, R with OpenBLAS and Revolution R Open: which is fastest?
Read a lot of datasets at once with R
Unit testing with R
Update to Introduction to programming econometrics with R
Using R as a Computer Algebra System with Ryacas

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 <- function(n){
a <- 0
b <- 1
for (i in 1:n){
temp <- b
b <- a
a <- a + temp
}
return(a)
}
```

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 <- (1 + sqrt(5))/2
psi <- (1 - sqrt(5))/2
expect_equal(Fibonacci(15), (phi**15 - psi**15)/sqrt(5))
})
```

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 know about Binet's formula, you could simply compute some numbers
by hand and compare them to what your function returns, for example. The function `expect_equal`

is a function from the
package `testthat`

and does exactly what it tells. We expect the result of our implementation to be equal to the result of
Binet's Formula. The file `test_fibo.R`

can contain as many tests as you need.
Also, the file that contains the tests must start with the string `test`

, so that `testthat`

knows with files it has to run.

Now, we're almost done, create yet another script, let's call it `run_tests.R`

and write the following code in it:

```
library(testthat)
source("path/to/fibo.R")
test_results <- test_dir("path/to/tests", reporter="summary")
```

After running these lines, and if everything goes well, you should see a message like this:

```
> library(testthat)
> source("path/to/fibo.R")
> test_results <- test_dir("path/to/tests", reporter="summary")
.
Your tests are dandy!
```

Notice the small `.`

over the message? This means that one test was run successfully. You'll get one dot per successful
test. If you take a look at `test_results`

you'll see this:

```
> test_results
file context test nb failed skipped error user system real
1 test_fibo.R Test Fibo(15) 1 0 FALSE FALSE 0.004 0 0.006
```

You'll see each file and each function inside the files that were tested, and also whether the test was skipped, failed etc. This may seem overkill for such a simple function, but imagine that you write dozens of functions that get more and more complex over time. You might have to change a lot of lines because as time goes by you add new functionality, but don't want to break what was working. Running your unit tests each time you make changes can help you pinpoint regressions in your code. Unit tests can also help you start with your code. It can happen that sometimes you don't know exactly how to start; well you could start by writing a unit test that returns the result you want to have and then try to write the code to make that unit test pass. This is called test-driven development.

I hope that this post motivated you to write unit tests and make you a better R programmer!