How to reuse examples in unit tests?

172 views Asked by At

Let's say I have a function, documented with an example (using roxygen):

#' @title Add two numbers
#' @param x a scalar
#' @param y a scalar
#' @examples 
#' testobj <- add(x + y)

add <- function(x, y) {
  return(x+y)
}

Now I also want to run some tests on the resulting object, to make sure the function does as it should. I'll use testthat for that:

context("Adding stuff")

testobj <- add(x, y) # THIS is the duplicate line that bothers me.

test_that(desc = "Additions work", code = {
  testthat::expect_length(object = x, n = 1)
})

How can I reuse the testobj created in the example and then run some tests on it in testthat?

It's trivial in this case, but it leads to substantial duplication if the function is more complex.

Or am I using this wrong?

1

There are 1 answers

0
ddisk On BEST ANSWER

You can use the example function exported from utils to run the examples contained in the documentation of a function.

testobj <- example(add)
# add> testobj <- add(x, y)

Note that it is recommended to use concrete examples in your roxygen comments:

Instead of

#' @examples 
#' testobj <- add(x, y)

Use

#' @examples 
#' testobj <- add(2, 3)