Unit Testing with testthat
Write test_that() blocks, use expectations, and run tests with devtools::test().
Why Unit Testing?
Unit tests automatically verify that individual functions behave correctly. They catch regressions when you change code, serve as executable documentation, and give you confidence to refactor safely. The testthat package is the standard testing framework for R packages.
Setting Up testthat
usethis::use_testthat() adds testthat to Suggests in DESCRIPTION, creates tests/testthat/, and creates the runner script tests/testthat.R. Run it once when initializing a new package.
# usethis::use_testthat()
#
# Creates:
# tests/
# testthat.R <- runner (do not edit)
# testthat/
# (empty — write test files here)
#
# Updates DESCRIPTION:
# Suggests: testthat (>= 3.0.0)
# Config/testthat/edition: 3