繁体   English   中英

如何在R testthat中同时测试消息和错误消息?

[英]How to test for a message and an error message simultaneously in R testthat?

我希望对产生连接的函数进行单元测试。 它在执行期间输出一条包含连接详细信息的消息。

我想测试以下内容:

  1. 该消息按预期显示( expect_message(fn(),"blah")
  2. 没有错误( expect_error(fn(),NA)
  3. 创建的对象是一个特定的类( 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")

PS expect_messageexpect_error函数使用像throws_error这样的函数, expect_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")

您还可以链接expect_messageexpect_error

fn1 <- function(){
  message("blah")
  obj<-"blah"
  stop("someError")
}
expect_error(expect_message(fn1()), "someError")
# or
expect_message(expect_error(fn1(), "someError"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM