R Unit Tests Example

Author

Matthew DeHaven

Published

March 31, 2024

There is a great chapter on unit tests in R Packages (2e).

Unit Tests for a Package

Your last assignment had you create a package and host in on Github.

This example will show how we can add unit tests to a package.

Create a Package

  • Open a new folder in VS Code (or clone an empty repository from Github)

  • Make sure you have devtools and usethis installed

  • Run usethis::create_package(".") in the terminal to convert the project to a package

Setup testthat

  • Run the following to add testthat to your package
usethis::use_testthat(3)

Adding a Basic Function

  • Create a new R script called “myfunc.r” in the “R/” folder

  • Add the following code

R/myfunc.r
myfunc <- function(a, b) {
  c <- a + b
  return(c)
}

Adding a new unit test

  • Add a new unit test by running the following,
usethis::use_test("myfunc")

This is equivalent to just

  • Adding a new “test-myfunc.r” to the “tests/testthat/” folder

Now we want to actually test our function.

  • Add the following code to the test file,
tests/testthat/test-myfunc.r
test_that("testing my function adds correctly", {
  expect_equal(myfunc(1, 3), 4)
  expect_equal(myfunc(1, 3), 5)  ## This test will fail
})

Running Tests

Since we are within a pacakge, we can run any of the following to run our tests:

  • devtools::check() which also checks a bunch of other things
  • devtools::test()
  • testthat::test_dir("test")