2

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

Lukas Weber
  • 455
  • 6
  • 13
  • Maybe you can use `options(warn=-1)` to delete warnings in your other script. I think it's a replicate of this post -> https://stackoverflow.com/questions/16194212/how-to-suppress-warnings-globally-in-an-r-script – Gowachin Feb 26 '20 at 16:55
  • Hey, thanks for your answer. I don't want to turn off the warnings globally, since the users need to get some warnings that I throw on specific incidents. I just don't want to see the warning in the test result, since I'm aware that this warning will be thrown (and even test for it). – Lukas Weber Feb 27 '20 at 12:02

1 Answers1

0

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")
})
Lukas Weber
  • 455
  • 6
  • 13