Introduction
testthat provides unit testing for R. It ensures code works correctly and prevents regressions.
Setup
install.packages("testthat")
library(testthat)
Basic Tests
test_that("description", {
expect_equal(1 + 1, 2)
expect_true(TRUE)
expect_false(FALSE)
})
Expectations
# Equality
expect_equal(actual, expected)
expect_identical(actual, expected)
# Comparisons
expect_gt(x, 5)
expect_lt(x, 5)
expect_gte(x, 5)
expect_lte(x, 5)
# Types
expect_is(x, "data.frame")
expect_type(x, "double")
# Strings
expect_match(x, "pattern")
expectgrep(x, "pattern")
Test Files
# Run tests
test_dir("tests/testthat")
# Run specific file
test_file("tests/testthat/test-file.R")
Summary
Unit tests ensure code correctness. Write tests for all important functions.