Search code examples
rexceptiontestthat

testthat dividing by zero


I'm wondering how to use the testthat package to check division by zero. By default, R returns Inf when trying to divide by zero. I, on the other hand, want to check if the user has somehow handled dividing by 0 and replaced it with some other result, such as some text like ("Don't divide by 0!").

The problem is this: user can replace the result with any text, not necessarily the one I use in the formula for testing. So how to check if the user has inserted anything other than the default Inf?

sample user view:

divide <- function(x, y) {
  if(y!=0) x/y 
  else
    "Do not divide by zero"
}

and test (so far):

test_that("divide by zero", {
  expect_equivalent(divide(2, 0),"Do not divide by 0")
})

The test will obviously fail due to different character strings.


Solution

  • If the user is writing a function that needs to divide but must handle dividing by zero in some way (other than the default of returning Inf), we could do:

    expect_false(is.infinite(divide(2, 0)))