How can I make testthat think I don't have a package installed?

I'd use mocking with testthat::with_mock(). I'm not sure of two things: whether you want/need to use a further package to mock a base R function (not possible with testthat nowadays) and how to mock the results for a function call with arguments so maybe something like

In the actual package code:

is_otherpackage_installed <- function(){
  requireNamespace("otherpackage", quietly = TRUE)
}
if (!is_otherpackage_installed()) {
    stop("Package \"otherpackage\" isn't installed", call. = FALSE)
  }

then in the test

test_that("otherpackage installation is checked", {
  with_mock(
  is_other_package_installed = function() FALSE,
  expect_error(blabla, 'Package \"otherpackage\"')
)
})

Note that with_mock() isn't documented in testthat's pkgdown website so maybe one is supposed to use mockery or mockr for mocking? :thinking:

7 Likes