如何在预期时使用 testthat 静音消息和警告

问题描述

为了开发包,我使用了 testthat。我想测试我的函数是否发送了正确的消息和警告。我想同时测试函数的结果。这就是我尝试这样做的方式:

## R/foo.r
foo <- function() {
  message("This is a message")
  warning("This is a warning")
  "This is a result"
}

我编写这些测试:

## tests/testthat/test-foo.R

test_that("foo works",{
  expect_equal(foo(),"This is a result")
  expect_message(foo(),"This is a message")
  expect_warning(foo(),"This is a warning")
})

但是现在当我运行测试时,我有这个:

Loading testWarnMess
Testing testWarnMess
v |  OK F W S | Context
/ |   0       | foo                                                                           This is a message
v |   3   2   | foo [0.3 s]                                                                   
----------------------------------------------------------------------------------------------
Warning (test-foo.R:2:3): foo works
This is a warning
Backtrace:
 1. testthat::expect_equal(foo(),"This is a result") test-foo.R:2:2
 4. testWarnMess::foo()

Warning (test-foo.R:3:3): foo works
This is a warning
Backtrace:
 1. testthat::expect_message(foo(),"This is a message") test-foo.R:3:2
 7. testWarnMess::foo()
----------------------------------------------------------------------------------------------

== Results ===================================================================================
Duration: 0.3 s

[ FAIL 0 | WARN 2 | SKIP 0 | PASS 3 ]
This is a message

如何防止在我预期的测试结果中出现消息和警告?

解决方法

这样做的一个好方法是使用副词 purrr::quietly

test_that("foo works",{
  qfoo <- purrr::quietly(foo)
  qfoo_call <- qfoo()
  expect_equal(qfoo_call$result,"This is a result")
  expect_equal(qfoo_call$message,"This is a message")
  expect_equal(qfoo_call$warning,"This is a warning")
})

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...