Introduction
A developer always pays his technical debts! And we have a debt to pay to the gods of coding best practices, as we did not present many unit tests for our functions yet. Today we will show how to efficiently investigate and improve unit test coverage for our R code, with focus on functions governing our RStudio addins, which have their own specifics.
As a practical example, we will do a simple resctructuring of one of our functions to increase its test coverage from a mere 34% to over 90%.
The pretty rewards for your tests
Contents
Fly-through of unit testing in R
Investigating test coverage within a package
Test coverage for RStudio addin functions
Rewriting an addin function for better coverage
Testing the rewritten function and gained coverage
TL;DR - Just give me the package
References
Fly-through of unit testing in R
Much has been written on the importance of unit testing, so we will not spend more time on convincing the readers, but rather very quickly provide a few references in case the reader is new to unit testing with R. In the later parts of the article we assume that these basics are known.
In a few words
devtools - Makes package development easier by providing R functions that simplify common tasks
testthat- Is the most popular unit testing package for R
covr- Helps track test coverage for R packages and view reports locally or (optionally) upload the results
For a start guide to use testthat within a package, visit the Testing section of R packages by Hadley Wickham. I would also recommend checking out the showcase on the 2.0.0 release of the testthat itself.
Investigating test coverage within a package
For the purpose of investigating the test coverage of a package we can use the covr package. Within an R project, we can call the package_coverage() function to get a nicely printed high-level overview, or we can provide a specific path to a package root directory and call it as follows:
# This looks much prettier in the R console ;)
covr::package_coverage(pkgPath)
## jhaddins Coverage: 59.05%
## R/viewSelection.R: 34.15%
## R/addRoxytag.R: 40.91%
## R/makeCmd.R: 92.86%
For a deeper investigation, converting the results to a data.frame might be very useful. The below shows the count of number of times that given expression was called during the running of our tests for each group of code lines:
covResults