我正在寻找对产生连接的函数进行单元测试。它输出一条消息,其中包含执行期间的连接详细信息。
我想测试以下内容:
- 消息按预期显示 (
expect_message(fn(),"blah")
) - 没有错误 (
expect_error(fn(),NA)
) - 创建的对象是一个特定的类 (
expect_is(fn(),"PostgreSQLConnection")
)
我可以做res<-fn()
然后执行 expect_is()
从中,但是如何在调用函数时对消息和(缺少)错误执行测试。
理想情况下,我想同时评估所有三个,这样我就可以在之后安全地关闭连接。
library(testthat)
fn<-function(){
message("blah")
obj<-"blah"
class(obj)<-c("PostgreSQLConnection",class(obj))
return(obj)
}
expect_message(fn(),"blah")
expect_error(fn(),NA)
expect_is(fn(),"PostgreSQLConnection")
附注expect_message
和expect_error
函数使用类似 throws_error
的函数这可能会或可能不会被弃用——文档在这一点上有点令人困惑。 ?throws_error
最佳答案
使用 testthat::evaluate_promise
您可以获得函数调用的各个方面,存储结果,然后测试需要测试的项目。
在这种情况下,代码变为:
library(testthat)
fn<-function(){
message("blah")
obj<-"blah"
class(obj)<-c("PostgreSQLConnection",class(obj))
return(obj)
}
res<-evaluate_promise(fn())
expect_equal(res$messages,"blah")
expect_equal(res$warnings,character())
expect_s3_class(res$result,"PostgreSQLConnection")
关于r - 如何在 R testthat 中同时测试消息和错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36332845/