[英]How to test for an error and specific error message using testthat in R
[英]How to test for a message and an error message simultaneously in R testthat?
我希望對產生連接的函數進行單元測試。 它在執行期間輸出一條包含連接詳細信息的消息。
我想測試以下內容:
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")
PS expect_message
和expect_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_message
和expect_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.