简体   繁体   中英

How to test in R with the package testthat that function ONLY works for classes with a specific input?

Let`s say I have an R function f(x) and I ONLY want it to work if the class of x is either a data frame or matrix

How can I test using the package testthat, that an error occurs for any input x that is not a data frame or a matrix?

Consider the following example:

library(checkmate)
library(testthat)

f <- function(x) {
  assert(test_data_frame(x), test_matrix(x))
  return(dim(x))
}

l <- list()
expect_error(f(l))            

In order to complete the task I would have to write a test for every possible input that I can imagine the user might put into the function. What I am looking for is a way to check that the function does not work for any classes of input but data.frame or matrix

You can do the following. First of all, you can stop the function if its input is neither a data frame nor a matrix. Include something like this in the function body:

stopifnot(is.data.frame(x) || is.matrix(x))

where x is your input.

After that, you can include something like this:

expect_error(my_function(vector()))

It is not a good testing strategy to test against any single possible input. What you should test against is whether the function fails if the input is neither a matrix nor a data frame. One test would suffice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM