Storing expectations as unit tests and running tests

Developing R Packages

Jasmin Ludolf

Content Developer

Workflow

  1. Create examples to show how our function works
  2. Write expectations to check function behavior
  3. Group expectations that test common aspect into a unit test
  4. Run all unit tests in a file
  5. Run all unit tests throughout a package

testing.png

Developing R Packages

Grouping similar function expectations together

expect_equal(temp_converter(32, "Fahrenheit", "Celsius"), 0)
expect_warning(temp_converter(-40, "Celsius", "Celsius"))
expect_error(temp_converter(300, "Kelvin", "Fahrenheit"))
library(testthat)

test_that("Conversion from F to C and C to F works", {
expect_equal(temp_converter(32, "Fahrenheit", "Celsius"), 0) expect_warning(temp_converter(-40, "Celsius", "Celsius")) expect_error(temp_converter(300, "Kelvin", "Fahrenheit")) })

test_example output

Developing R Packages

What if tests failed?

library(testthat)
test_that("Conversion from F to C and C to F works", {
      expect_equal(temp_converter(32,  "Fahrenheit", "Celsius")), 1)
      expect_warning(temp_converter(-40), "Celsius", "Fahrenheit")
      expect_error(temp_converter(25)) 
})
X Conversion from F to C and C to F works
-- 1. Error: `temp_converter(32,  "Fahrenheit", "Celsius")` not equal to 1 
(@test_conversion.R:2) 
--
-- 2. Error: `temp_converter(-40)` did not throw the expected warning. 
(@test_conversion.R:3) 
--
temp_converter(25) did not throw an error.
Developing R Packages

Running all tests in a file

  • To run all of the tests in a file, use test_file()
library(testthat)
test_file("test-temp_conversion.R")
Conversion from F to C and C to F works
Developing R Packages

Run tests on the examples

#' @examples
#' # Convert 25 degrees Celsius to Fahrenheit 
#' temp_converter(25, unit_from = "Celsius", unit_to = "Fahrenheit")
#' # Convert 100 degrees Fahrenheit to Celsius 
#' temp_converter(100, unit_from = "Fahrenheit", unit_to = "Celsius")
  • roxygenize() generates a help file for temp_converter in man directory
test_example("man/temp_converter.Rd")

test_example output

Developing R Packages

You gotta run 'em all!

  • Use test_file() if you want to focus on a particular file
  • Don't have to run test_file() on each testing file each time
  • Can instead run test_package() to run them all!
test_package("unitConverter")
Developing R Packages

Let's practice!

Developing R Packages

Preparing Video For Download...