Unit tests

R-Pakete entwickeln

Jasmin Ludolf

Content Developer

R package structure

Example package structure

R-Pakete entwickeln

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

R-Pakete entwickeln

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

R-Pakete entwickeln

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

R-Pakete entwickeln

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
R-Pakete entwickeln

A function for creating these files

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

use_test temp_converter

use_test time_converter

R-Pakete entwickeln

Let's practice!

R-Pakete entwickeln

Preparing Video For Download...