错误消息中的括号导致 expect_error 测试失败

Parentheses in error message cause expect_error test to fail

为什么这个测试没有通过?

my_fun <- function(x){
  if(x > 1){stop("my_fun() must be called on values of x less than or equal to 1")}
  x
}

library(testthat)
expect_error(my_fun(2),
             "my_fun() must be called on values of x less than or equal to 1")

它returns错误信息:

Error: error$message does not match "my_fun() must be called on values of x less than or equal to 1". Actual value: "my_fun() must be called on values of x less than or equal to 1"

如果您从函数和测试中删除 (),测试 通过,这让我认为它与括号有关。

expect_error 中,您传递的是正则表达式,而不仅仅是字符串。括号是正则表达式中的特殊字符,必须进行转义。 (括号用于在正则表达式中分组)。要处理括号,只需将 expect_error 更改为以下内容:

expect_error(my_fun(2),
             "my_fun\(\) must be called on values of x less than or equal to 1")

或者更一般地说,指定 fixed = TRUE 以将字符串测试为完全匹配:

expect_error(my_fun(2),
             "my_fun() must be called on values of x less than or equal to 1",
             fixed = TRUE)