testthat Exercises in R: 15 Practice Problems

Fifteen practice problems on testthat: expectations, fixtures, error matching, snapshots, mocks.

RInteractive R
library(testthat) library(devtools)

  

Exercise 1: expect_equal

Show solution
RInteractive R
test_that("addition works", { expect_equal(1 + 1, 2) })

  

Exercise 2: expect_identical

Show solution
RInteractive R
test_that("identical objects", { expect_identical(1L, 1L) })

  

Exercise 3: expect_true / expect_false

Show solution
RInteractive R
expect_true(2 > 1); expect_false(2 < 1)

  

Exercise 4: expect_error

Show solution
RInteractive R
expect_error(stop("bad"), "bad")

  

Exercise 5: expect_warning

Show solution
RInteractive R
expect_warning(as.numeric("a"))

  

Exercise 6: expect_message

Show solution
RInteractive R
expect_message(message("hi"), "hi")

  

Exercise 7: expect_silent

Show solution
RInteractive R
expect_silent(1 + 1)

  

Exercise 8: expect_length

Show solution
RInteractive R
expect_length(1:5, 5)

  

Exercise 9: Tolerance

Show solution
RInteractive R
expect_equal(1.0001, 1, tolerance = 0.01)

  

Exercise 10: skip_if_not_installed

Show solution
RInteractive R
test_that("uses ggplot2", { skip_if_not_installed("ggplot2") expect_true(TRUE) })

  

Exercise 11: expect_named

Show solution
RInteractive R
expect_named(c(a = 1, b = 2), c("a","b"))

  

Exercise 12: expect_snapshot

Show solution
RInteractive R
# expect_snapshot(print(mtcars[1:3, ]))

  

Exercise 13: Test setup with fixture

Show solution
RInteractive R
test_that("uses fixture", { d <- mtcars[1:3, ] expect_equal(nrow(d), 3) })

  

Exercise 14: Mock with local_mocked_bindings

Show solution
RInteractive R
# local_mocked_bindings(Sys.time = function() as.POSIXct("2024-01-15"))

  

Exercise 15: Run all tests

Show solution
RInteractive R
# devtools::test() # in a package

  

What to do next

  • R-Package-Development-Exercises (shipped), testing fits inside packages.
  • R-Debugging-Exercises (coming), when tests fail.

Ready to earn the testthat Certificate?

The quiz is concept-based and respects your time: pass it once and your verifiable certificate is yours to share on LinkedIn, your resume, or your portfolio. Take it when you feel comfortable with the material.

Attempt the quiz