簡體   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