NHS R Conference 2023
Priyanka Gagneja
Oct 10,2023
Priyanka Gagneja
Lead Analyst at OnPoint Insights
Big Fan of R community
A function
Robust
In a growing codebase, you will need unit tests. Sometimes even small scripts can sometimes produce a lot of distress.
– André Müller
The three right answers are:
“A software system can best be designed if the testing is interlaced with the designing instead of being used after the design”
– Alan Perlis, NATO Software Engineering Conference, 1968 (source https://www.infoq.com/presentations/1-9-6-8)
Test the behaviour of your unit, not its implementation
library(testthat)
# Write a function
rescale <- function(x, r.out) {
p <- (x - min(x)) / (max(x) - min(x))
r.out[[1]] + p * (r.out[[2]] - r.out[[1]])
}
# Experiment
# x <- rnorm(20)
# r.out <- c(0.1, 1.4)
# range(rescale(x, r.out)) == r.out
# Write a formal unit test
testthat::expect_that(range(rescale(x, r.out)), equals(r.out))
# testthat::expect_equal(range(rescale(x, r.out)), r.out)The easiest way to get started is with usethis.
Assuming you’re in project directory, run usethis::use_test("function-name") , e.g usethis::use_test("rescale") to create a test file, and set up all the other infrastructure you need.
Run tests in a single file - test_file(path = "./tests/testthat/test-rescale.R")
If you’re using RStudio, press Cmd/Ctrl + Shift + T (or run devtools::test() if not) to run all the tests in a package.
Seems like extra work but will save you time * Decreased frustration. Bugs appear very close to hard deadlines. Testing allows to quickly identify where the problem is and fix it.
More confidence in the code * Better code structure. Code that is easy to test is usually better designed. Tests sometimes make you see large complicated functions and break them down into smaller, more manageable chunks.
Make changes or updates without worrying too much * Make changes confidently because you know your tests will catch any issues.
Reach Me - priyankaigit@gmail.com; www.linkedin.com/in/priyanka-gagneja; https://www.twitter.com/priyankaigit