Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw warnings rather than errors in testthat

Tags:

r

testthat

I'm writing unit tests for a package and there are some tests where I don't want the tests to throw errors if they fail but to instead give warnings.

This isn't my real code, but let's say I want to test something like:

add_x_y <- function(x, y) x + y
expect_equal( add_x_y(2, 2), 3 )

The output is an error:

Error: add_x_y(2, 2) not equal to 3.
1/1 mismatches
[1] 4 - 3 == 1

Is there a variant or alternative function that would throw a warning rather than an error for this check?

like image 741
bschneidr Avatar asked Oct 24 '25 17:10

bschneidr


1 Answers

In the absence of an approach specific to testthat you could use general error handling to output a warning in place of an error.

expect_equal_or_warn <- function(...) tryCatch(expect_equal(...),
                                               error = function(e) warning(e))

expect_equal_or_warn(add_x_y(2,2), 3)

Warning message:
add_x_y(2, 2) not equal to 3.
1/1 mismatches
[1] 4 - 3 == 1 
like image 175
Ritchie Sacramento Avatar answered Oct 26 '25 08:10

Ritchie Sacramento



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!