我的一个函数抛出了多个警告,我想用 来测试一下testthat::expect_warning()
。我可以检查一下设计,但文档似乎说这是可能的,使用已弃用的参数all
:
all
:已弃用如果您需要测试多个警告/消息,您现在需要多次调用 expect_message()/ expect_warning()
(感谢这个答案后的评论)
在下面的 reprex 中(受文档示例启发),devtools::check()
正在通过。 devtools::test()
也正在通过,但它也会引发警告(当测试特定警告时,会引发另一个警告)。
由于所有警告都是预期的,那么测试多个警告的正确方法是什么?
f1.R
f1 <- function(x) {
if (x < 0) {
warning("*x* is already negative")
warning("this is a second warning")
return(x)
}
-x
}
测试-f1.R
test_that("testing", {
# Testing the function
expect_equal(f1(2), -2)
# Testing a generic warning
expect_warning(f1(-1))
# Testing the first warning
expect_warning(f1(-1), "already negative")
# Testing the second warning
expect_warning(f1(-1), "second")
# Testing no warning
expect_warning(f1(1), NA)
})
相关输出test()
对应于expect_warning(f1(-1))
警告(test-f1.R:5:3):测试这是第二个警告
对应于expect_warning(f1(-1), "already negative")
警告(test-f1.R:6:3):测试这是第二个警告
对应于expect_warning(f1(-1), "second")
警告(test-f1.R:7:3):测试x已经为负数
我认为你不能直接用 来做这件事
expect_warning
,但你可以capture_warnings
用 来检查所有预期的事情。使用
sapply
警告消息向量应确保您获得每种模式中的至少一个。编写自定义期望并不难:
根据您的需要和偏好,您可能想要/需要玩耍
...
和/或争论。grepl(.)
我终于找到了这篇关于 testthat 第三版的
vignette("third-edition",package ="testthat")
短文/文章。调用之间可以使用管道。expect_warning()
本文还讨论了第二版的行为。