How to test that an error does not occur?
For example:
context("test error")
test_that("test error 1", {
expect_true({log(10); TRUE})
})
test_that("test error 2", {
expect_true({log("a"); TRUE})
})
will test if there is an error.
> test_file("x.r")
test error : .1
1. Error: test error 2 -------------------------
Non-numeric argument to mathematical function
1: expect_true({
log("a")
TRUE
})
2: expect_that(object, is_true(), info, label)
3: condition(object)
4: expectation(identical(x, TRUE), "isn't true")
5: identical(x, TRUE)
this means the first part passed the test while the second part failed.
Major edit due to changes in testthat
Since version 0.11 (via RStudio blog) there is direct support to testing lack of errors:
expect_error(myfun(), NA)
Same for catching warning
and message
:
expect_warning(myfun(), NA)
expect_message(myfun(), NA)
Side note: There is an info
parameter in expect_xxx
functions to pass additional info. So you can do:
for (i in 1:17) expect_error(myfun(), NA, info = paste("i =", i))
Here is one solution using the expectation that tryCatch
returns 0
when the error does not occur:
expect_equal(tryCatch(for(i in 1:17) myfun()), 0)
Maybe wrap it with another expect_error.
Example:
expect_error(1)
expect_error(expect_error(1))