简体   繁体   中英

How to test for an error and specific error message using testthat in R

I am attempting to write a test that ensures that, given a certain input, a function

  1. errors
  2. provides a specific error message

I am using testthat::expect_error()

Example

As a very simple, reproducible example suppose we have a multiplication function

test_funct <- function(x) { x * 2 } 

And a very simple test to test that it errors when provided an input of class character:

test_that(
  "function errors when it receives a character object", 
  { test_funct("a") %>% expect_error("non-numeric argument to binary operator") } 
  )

The problem

I was expecting this test to pass, since "a" is of class character and would indeed produce the error message provided to expect_error() (ie "non-numeric argument to binary operator" ).

However, the test does not pass, instead returning:

Error: Test failed: 'function errors when it receives a character object'
* non-numeric argument to binary operator
1: test_funct("a") %>% expect_error("non-numeric argument to binary operator")
2: eval(lhs, parent, parent)
3: eval(lhs, parent, parent)
4: test_funct("a")

How can I create a test that checks that a function errors and provides a certain error message?

Don't use the pipe operator. It should work, but it throws the error you get. At least with testthat version 2.0.1. If I use the none pipe code like below, the test passes.

test_that(
  "function errors when it receives a character object", 
  { expect_error(test_funct("a"), "non-numeric argument to binary operator") } 
)

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