5

I'm looking to unit test a function that produces a connection. It outputs a message that contains the connection details during execution.

I want to test the following:

  1. The message appears as expected (expect_message(fn(),"blah"))
  2. There is no error (expect_error(fn(),NA))
  3. Object created is a specific class (expect_is(fn(),"PostgreSQLConnection"))

I could do res<-fn() and then do the expect_is() from it, but how can I perform tests on both the message and the (lack of an) error whilst calling the function.

Ideally, I'd like to evaluate all three simultaneously and in such a way I could then safely close the connection afterwards.

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 The expect_message and expect_error functions use functions like throws_error which may or may not be deprecated- the docs are a little confusing on that point. ?throws_error

4

2 回答 2

4

使用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")
于 2016-03-31T12:06:29.853 回答
0

您还可以链接expect_messageexpect_error

fn1 <- function(){
  message("blah")
  obj<-"blah"
  stop("someError")
}
expect_error(expect_message(fn1()), "someError")
# or
expect_message(expect_error(fn1(), "someError"))
于 2020-06-15T09:48:09.723 回答