Introduction

Up until now, your workflow probably looks like this:

  1. Write a function.
  2. Load it with or devtools::load_all().
  3. Experiment with it in the console to see if it works.
  4. Go back to 1.

While this is testing, sometimes a more formal approach is better.

Let’s start by setting up our package to use the testthat: usethis::use_testthat().

Unit tests

Advantages:

  1. Better code, you are explicit about how the code behaves
  2. Better structure, many small components working together
  3. Easier to start up, all your tests are documented in a script
  4. Fearless development, don’t have to worry about unknowingly breaking something

Unit tests with testthat are defined in terms of expectations. The package provides a suite for functions that have the expect_ prefix that compare the values of different objects:

library(testthat)
expect_equal(1, 1 + 1)
## Error: 1 not equal to 1 + 1.
## 1/1 mismatches
## [1] 1 - 2 == -1
expect_lt(1, 1 + 1)

General principles:

  1. When you are tempted to write a “print” statement, write a test instead.
  2. Write tests for complex code with lots of interdependencies
  3. Write a test when you discover a bug.

Example

Organizing tests

Alternatives

devtools::check()