Unit tests

Developing R Packages

Jasmin Ludolf

Content Developer

R package structure

Example package structure

Developing R Packages

Testing your code works

  • Documentation helps our users
  • And helps the package author with development and maintenance
  • Manually checking functions can be difficult

User testing code

Developing R Packages

What are unit tests?

  • Automated and run all at once
  • Verify functionality of package units
  • Ensure expected behavior and correct output
  • Catch bugs early
  • Support clean and testable code, supporting collaboration

Automation cheers

Developing R Packages

Structuring unit testing in R

  • Testing framework with usethis + testthat
library(usethis)

use_testthat()
  • testthat package: simple and intuitive syntax for writing unit tests

use_testthat() output :

use_testthat output

Developing R Packages

Creating test template files

  • Match names of .R files in R directory to names in tests/testthat
    • R/temp_converter.R
    • R/time_converter.R
  • Corresponding files in tests/testthat
    • tests/testthat/test-temp_converter.R
    • tests/testthat/test-time_converter.R
Developing R Packages

A function for creating these files

use_test(name = "temp_converter")
use_test(name = "time_converter")

use_test temp_converter

use_test time_converter

Developing R Packages

Let's practice!

Developing R Packages

Preparing Video For Download...