0Pricing
R Academy · Lesson

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

All lessons in this course

  1. Package Structure with usethis and devtools
  2. Documenting Functions with roxygen2
  3. Unit Testing with testthat
  4. CRAN Submission and Package Maintenance
← Back to R Academy