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:
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
Continue reading “Testing in R”