Testing in R

To test a given function in R, I use the package ‘testthat’.

A very nice intro to the package is present here: https://journal.r-project.org/archive/2011/RJ-2011-002/RJ-2011-002.pdf

However, in order to write good quality code and to do it only once, you got to carry out a paradigm shift in your writing procedure:

How to write a tests-oriented program

You might have the natural tendency to write the tests after your code.

However, this is not the best approach, indeed, after that, you might need to rewrite big part of the code, to make it more ‘testable’.

In order to avoid that, you need to write your test before the program.

Certainly, this is is a bit harder to implement, especially the first times.

Therefore, to make it easier, follow these guidelines:


  • Independent files:
    • One for the program, one for the tests
  • Code stile for the program:
    • Atomicity:
      • A single R file for each task/objective.
      • Single functions for each step of your algorithm. This will help later in the test
    • A main function to be invoked. This will list all the functions (steps) of the program.
  • Tests, in and out:
    • Within the program file
      • Tests that define and check the inputs
      • Tests that define and check the outputs
    • Within the test file
      • A test with correct inputs
      • Wrong inputs
      • Exceptions

File needed

For each given function create a test-file within a path similar to this:

If you need to some files to test your function save in a path similar to this:

Code stile for the program

Test Examples

Let’s consider two simple function:

Three are the main kind of test I suggest to use: One that test if the result is correct, one that is not correct, one the deals with error and exception.

Structure of a test-file:

It is probably not correct practice but I advise to live the packages needed and function to be tested as comment at the beginning of the file.



Mocking a function

By mocking a function we want to force a particular output from a function that can be encountered during the test.

In this way, you can avoid to use Function1, because it takes too much time to run, or simply cannot be used right now, so we mock it.

This means that next time Function2 looks for Function1, it is redirected to use the result of m


Stubbing is similar to mocking but, Stub, is simple fake object. It just makes sure that the test runs smoothly.

Instead, mock is smarter stub. That verifies your test passes through it.

More in https://github.com/MattiaCinelli/notes/blob/master/Notes%20on%20R%20testing.ipynb

0 0 vote
Article Rating
Notify of
Inline Feedbacks
View all comments