Search code examples
runit-testingtestingtestthat

R: How to omit tested warning message from test report when testing for result AND warning


I want to test in R if a function

  1. returns the correct value
  2. throws the correct warning during calculation

For that, I created a reproducible example. There a two scripts, the first one (e.g. test-warning-and-result.R) works fine and without any errors:

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")
})

However, when I run the tests from an external script (e.g. run-test.R), it logically throws a warning at "x = f(-1)"

library(testthat)
test_dir(".")

Picture of test results

Since I know there will be a warning and am testing for it, I'm searching for a way to omit the warning within test_that() from the test report. Ideally, I would not have to run the function twice but in one test.

Any Ideas would be appreciated


Solution

  • Ok after having one night's sleep on it I found a simple sollution:

    Don't store the functions result in a variable x. Nest the two tests into each other, with the expect_warning outside

    Change from

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

    to

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