Elegant way to test for absolute differences via testthat::expect_equal()

Viewed 23

I am currently implementing unit tests with testthat::expect_equal(). For testthat version 3, this tests for relative differences unless the difference between the input values is very small, in which case, the test is based on an absolute difference measure. Is there an elegant way to force expect_equal to use an absolute distance measure, even when the differences between $x$ and $y$ are not small?

Here is a link to the documentation of expect_equal.

Thanks!

1 Answers

One way to test for absolute difference is of course via expect_true() - e.g. assume that X = 1, Y = 1.05 and the absolute difference is allowed to be 0.1.

Then one can write

library(testthat)

X <- 1
Y <- 1.05
tolerance <- 0.1
expect_true(abs(X - Y) < tolerance)
Related