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
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
- Create a new functionality.
- 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
null, and minimum or maximum possible input values.
- Load the edits you made and test the package with
- Modify your code to fix failing test cases.
- Repeat until all tests pass.
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.