usethis::use_testthat(3)R package: tests
RSE
Rpkg
Notes on tests, with the use of testthat package
Useful references:
- GSWEP4R: Ensuring Quality by Matt Secrest
- R packages (2e) Chapter 13, 14, 15 by Hadley Wickham and Jenny Bryan
Unit test: tests whether your function returns values as expected.
Benefits:
- Fewer bugs
- Better code structure, thhe functions need to be better designed
Example situations:
- missing values in the data;
- zero standard deviation (same values; or one value for the group)
- infinity
Use testthat in a package
1. Initialize
Create tests/testthat/ directory
This creates the directory with
- an empty folder
testthatwhere you write your tests - an R script
testthat.Rwhere tests are run whenR CMD checkis run. Do not modify this file.
2. Create a test
Test files must have names that start with test. For example, a function is R/fn_name.R, then test is tests/testthat/test-fn_name.R.
usethis::use_test('testname')3. Run a test
testthat::test_file('tests/testthat/test-foofy.R')- Run Tests button
devtools::test()for entire test suite. Cmd + Shift + Tdevtools::check()
A workflow worked for me
- Create a simple function
- Create a test file immediately, with clear naming. Inside this test file, can write various tests for the same function.
- have at least a test that expects the correct result (
expect_identical()or else) - have at least a test that expects error, (
expect_error()). Inside the original function, error should be thrown byrlang::abort().
- Run test
- Run test coverage,
covr::package_coverage()orcovr::code_coverage() - Check