Introduction
Up until now, your workflow probably looks like this:
- Write a function.
- Load it with or
devtools::load_all()
.
- Experiment with it in the console to see if it works.
- 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:
- Better code, you are explicit about how the code behaves
- Better structure, many small components working together
- Easier to start up, all your tests are documented in a script
- 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:
- When you are tempted to write a “print” statement, write a test instead.
- Write tests for complex code with lots of interdependencies
- Write a test when you discover a bug.
Example
- What bug did we discover in the sampling function?
- What is the expected behavior in this case and how does it fail?
- Let’s write a test!
Organizing tests
Alternatives
- You don’t have to use
testthat