Chapter: 4 Unit Testing

Likely as not, you have already written scripts that demonstrate that your script runs and produces a desired results. Unit testing, via the testthat package (Wickham 2011), formalizes this process and automates many of these scripts at once to make running a comprehensive test set easy to do. Read up about testing and automated checking

4.1 Test Scripts

Each time you write a user-facing or non-trivial function, you should write a test script that verifies that the function returns the result you expected in all individual cases. These test files live in tests/testthat/. The file name must start with “test” and it should indicate which function or functionality is being tested.

4.2 An Example Test

test_that("multiplication works", {
  actual = 2 * 2
  expected = 4
  expect_equal(actual, expected)
})

4.3 Expectations

Expect functions are those at the end of test each test case that allow you to check the output of your function against what you expect. There are many kinds of these functions, the most common being expect_equal(). If need be, there are more complicated ways to express expectation such as expect_lt() that passes when the returned value is less than the specified value, or expect_error() that expects an error to be thrown instead of a return value. A comprehensive list can be found here.

4.4 Testing Workflow

  1. Create a new functionality.
  2. Write a series of tests in a new file to verify your function behaves the way you expect in every scenario, including edge cases, with parameters like 0, null, and minimum or maximum possible input values.
  3. Load the edits you made and test the package with devtools::test().
  4. Modify your code to fix failing test cases.
  5. Repeat until all tests pass.

References

Wickham, Hadley. 2011. “Testthat: Get Started with Testing.” The R Journal 3: 5–10. https://journal.r-project.org/archive/2011-1/RJournal_2011-1_Wickham.pdf.