我的一个函数抛出了多个警告,我想用 来测试一下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已经为负数