Testing

Mini-Lecture 17

Ben Baumer

Smith College

2024-11-14

Testing

testthat

How do you know if something works?

square <- function(x) {
  if (!is.numeric(x)) {
    stop(paste0("x must be numeric, but '", x, "' is not"))
  }
  x * x
}
square(2) == 4
[1] TRUE
library(testthat)
expect_equal(square(2), 4)

Multiple expectations

test_that("square works", {
  # test a simple case
  expect_equal(square(0), 0)
  
  # test against known value
  expect_equal(square(-1), 1)
  # test against base R function
  expect_equal(square(-1), 1^2)
  # test against itself
  expect_equal(square(-1), square(1))
  
  # test a range of values
  expect_equal(square(1:10), (1:10)^2)
  
  # weird edge cases
  expect_equal(square(-Inf), Inf)
})
Test passed 😸

Classes

test_that("classes and data types are correct", {
  expect_is(square(2), "numeric")
  expect_is(square(2L), "integer")
  expect_is(square(pi), "numeric")
})
Test passed 🎉

Errors

"a"^2
Error in "a"^2: non-numeric argument to binary operator
square("a")
Error in square("a"): x must be numeric, but 'a' is not
expect_error(square("a"), "but")

When to write a test

  • Always test basic functionality

Whenever you are tempted to type something into a print statement or a debugger expression, write it as a test instead

–Martin Fowler

Always write a test when you discover a bug.

–Hadley Wickham

Once you’ve written your tests

devtools::test()

Now

Homework