R 建议的依赖项未与testthat一起安装时的测试包行为

R 建议的依赖项未与testthat一起安装时的测试包行为,r,testing,dependencies,r-package,testthat,R,Testing,Dependencies,R Package,Testthat,我有一个包,其中包含一个支持可选行为的建议依赖项 按照最佳实践,我在“建议”中添加了此依赖项,并在使用它之前检查它是否安装了requireNamespace 在这个特殊的例子中,建议的包是data.tree,可选的行为是打印漂亮的图片,而不是更无聊的图片 myfun <- function(...) { if (requireNamespace("data.tree", quietly = TRUE)) { # do pretty print } els

我有一个包,其中包含一个支持可选行为的建议依赖项

按照最佳实践,我在“建议”中添加了此依赖项,并在使用它之前检查它是否安装了
requireNamespace

在这个特殊的例子中,建议的包是
data.tree
,可选的行为是打印漂亮的图片,而不是更无聊的图片

myfun <- function(...) {
  if (requireNamespace("data.tree", quietly = TRUE)) {
    # do pretty print
  } else {
    # do boring print
  }
}

是否有一种方法可以通过
testthat
模拟缺少的依赖项,或者更一般地说,有一种方法可以测试
myfun

一种可能是创建两个不同的库文件夹。一个可以有
data.tree
包,另一个则没有,您可以使用不同的
.libpath()
运行代码。withr::with_libpath的
可以帮助设置/取消设置这些值。
test_that("myfun does a pretty print with data.tree", {
  myfun()
})

test_that("myfun does a boring print if data.tree is not installed", {
  # Ideally I am looking for a bit of code like this: 
  with(simulate_missing("data.tree"), 
       myfun())
})