首页 > 解决方案 > R:如何在测试结果和警告时从测试报告中省略测试警告消息

问题描述

我想在 R 中测试一个函数

  1. 返回正确的值
  2. 在计算过程中抛出正确的警告

为此,我创建了一个可重现的示例。有两个脚本,第一个(例如test-warning-and-result.R)工作正常且没有任何错误:

library(testthat)

f <- function(x) {
  if (x < 0) {
    warning("*x* is already negative")
    return(x)
  }
  -x
}

test_that("warning and result", {
  x = f(-1)
  expect_that(x, equals(-1))
  expect_warning(f(-1), "already negative")
})

但是,当我从外部脚本(例如run-test.R)运行测试时,它在逻辑上会在“x = f(-1)”处引发警告

library(testthat)
test_dir(".")

测试结果图片

因为我知道会有一个警告并且正在测试它,所以我正在寻找一种方法来从测试报告中省略 test_that() 中的警告。理想情况下,我不必在一次测试中运行该函数两次。

任何想法,将不胜感激

标签: runit-testingtestingtestthat

解决方案


好吧,睡了一晚之后,我找到了一个简单的解决方案:

不要将函数结果存储在变量 x 中。将两个测试相互嵌套,将 expect_warning 放在外面

从改变

test_that("warning and result", {
  x = f(-1)
  expect_that(x, equals(-1))
  expect_warning(f(-1), "already negative")
})

test_that("warning and result", {
  expect_warning(expect_that(f(-1), equals(-1)), "already negative")
})

推荐阅读