01 / 21

Unit Testing with
testthat

Learn how to write reliable, automated tests for your R code using test_that() and expect_equal(): the foundation of professional R development.

R Programming

What Is Unit Testing?

A unit test is a small, automated check that verifies one specific behavior of your code. Instead of manually running your function and eyeballing results, you write code that tests your code.

Automated
Tests run with a single command: no manual checking needed
Repeatable
Run the same tests every time you change your code
Specific
Each test targets one small behavior, making bugs easy to find

Why Use testthat?

testthat is the most popular testing framework for R. It gives you a clear, readable way to describe what your code should do and check that it actually does it.

Catch Bugs Early
Find problems the moment they appear, not weeks later
Refactor Safely
Change code confidently knowing tests will catch regressions

The Two Building Blocks

test_that() Describes WHAT you are testing expect_equal() expect_true() test_that() The container Groups related checks expect_*() The assertions Check actual vs expected

Anatomy of test_that()

test_that("description of behavior", { # Setup result <- my_function(10) # Assertion expect_equal(result, 20) })
1
Description string: a human-readable sentence explaining what behavior you are testing
2
Code block { }: contains setup code and one or more expect_*() calls
3
Expectation: compares the actual result to the expected value

Anatomy of expect_equal()

expect_equal( # What your code actually produces add(2, 3), # What you expect it to produce 5 )
ACTUAL add(2, 3)
\(=\)
EXPECTED 5 ✓ Test passes if they match

test_that() vs expect_equal()

test_that() expect_equal()
Role Container / organizer Individual assertion
Arguments Description string + code block Actual value + expected value
How many? One per behavior One or more per test_that()
Analogy A test case envelope A single True/False check inside
On failure Reports which test failed Reports what value was wrong

The expect_* Family

expect_equal() is the most common, but testthat provides a whole family of assertion functions for different situations:

expect_equal()
Checks that actual equals expected (with tolerance for floats)
expect_true()
Checks that an expression evaluates to TRUE
expect_error()
Checks that code throws an error (for testing bad inputs)
expect_length()
Checks that a vector has the expected number of elements

Writing Tests: Step by Step

1
Install and load testthat: run install.packages("testthat") once, then library(testthat)
2
Write your function first: define the function you want to test (e.g., add())
3
Think of expected behavior: "What should this function return for a given input?"
4
Write a test_that() block: give it a clear description and add expect_equal() assertions
5
Run and read the output: a pass means it works, a fail shows you what went wrong

Example 1: Testing add()

# The function add <- function(x, y) { x + y } # The test test_that("add returns the sum of two numbers", { expect_equal(add(2, 3), 5) expect_equal(add(0, 0), 0) expect_equal(add(-1, 1), 0) })

Example 2: Testing Edge Cases

celsius_to_fahrenheit <- function(c) { c * 9/5 + 32 } test_that("celsius_to_fahrenheit converts correctly", { expect_equal(celsius_to_fahrenheit(0), 32) expect_equal(celsius_to_fahrenheit(100), 212) expect_equal(celsius_to_fahrenheit(-40), -40) })

Example 3: When a Test Fails

# A buggy function multiply <- function(x, y) { x + y # Bug! Should be x * y } test_that("multiply returns the product", { expect_equal(multiply(3, 4), 12) })
## Error: Test failed ## "multiply returns the product" ## multiply(3, 4) not equal to 12. ## 1/1 mismatches ## [1] 7 - 12 == -5

The Testing Workflow

Write Function code Test Run test_that() Fail? Fix the bug Pass? Ship with confidence Red → Green → Refactor

Floating-Point Tolerance

Computers store decimal numbers with tiny rounding errors. The value \(0.1 + 0.2\) is not exactly \(0.3\) internally. expect_equal() handles this with a built-in tolerance.

# This would FAIL with exact comparison 0.1 + 0.2 == 0.3 # FALSE! # But expect_equal() passes (default tolerance) expect_equal(0.1 + 0.2, 0.3) # ✓ Pass # For EXACT match, use expect_identical() expect_identical(0.1 + 0.2, 0.3) # ✕ Fail

Common Mistakes

✕ Swapped Arguments
Putting the expected value first and the actual value second. Always: expect_equal(actual, expected).
✕ Vague Descriptions
Using "it works" as a test name. Be specific: "add returns the sum of two positive integers".
✕ Forgetting library(testthat)
Running test_that() without loading testthat first. Always call library(testthat) at the top of your test file.
✕ Testing Too Much
Putting unrelated checks in one test_that(). Each test should cover one specific behavior.

Quick Reference Table

Function Purpose Example
test_that() Group related assertions test_that("desc", { ... })
expect_equal() Check value equality expect_equal(f(2), 4)
expect_true() Check TRUE condition expect_true(is.numeric(x))
expect_error() Check error is thrown expect_error(f("bad"))
expect_identical() Exact match (no tolerance) expect_identical(x, "hello")
expect_length() Check vector length expect_length(v, 3)

Question 1 of 5

What is the primary role of test_that() in the testthat framework?

Question 2 of 5

Given the function square <- function(x) \(x^2\), which test is written correctly?

Question 3 of 5

In expect_equal(actual, expected), what does the first argument represent?

Question 4 of 5

Why does expect_equal(0.1 + 0.2, 0.3) pass, even though 0.1 + 0.2 == 0.3 returns FALSE in R?

Question 5 of 5

The test fails. What is the most likely reason?