Sebastian
Sebastian

Reputation: 939

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

Upvotes: 1

Views: 570

Answers (1)

slava-kohut
slava-kohut

Reputation: 4233

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.

Upvotes: 2

Related Questions