I'm not sure I follow your function exactly.
I've made an example package GitHub - maelle/menutests: What the Package Does (One Line, Title Case) with tests for one of the versions of the functions. Note that it's a stupid function as one probably never wants to reveal secrets.
reveal_secret <- function(secret, ok = ask()) {
if (is.null(ok)) {
stop("A value is needed for `ok` see ?reveal_secret")
}
if (ok) {
message(secret)
} else {
message("Nothing done.")
}
}
ask <- function() {
switch(
utils::menu(c("yes", "no"), title = "Ok to print secret?"),
TRUE, FALSE
)
}
(NULL is the case where the user types 0 instead of using one of the menu choices).
The function has an argument whose default value comes from using the menu function.
In the tests I can either
- use a value for that argument
test_that("reveal_secret works", {
expect_message(reveal_secret("top-secret", ok = TRUE), "top-secret")
expect_message(reveal_secret("top-secret", ok = FALSE), "Nothing")
})
- or use mocking. with mockery one cannot mock base R functions but I can mock
ask()
.
test_that("reveal_secret works, mocking", {
mockery::stub(where = reveal_secret, what = "ask", how = TRUE)
expect_message(reveal_secret("top-secret"), "top-secret")
})
test_that("reveal_secret works, mocking 2", {
mockery::stub(where = reveal_secret, what = "ask", how = FALSE)
expect_message(reveal_secret("top-secret"), "Nothing")
})
test_that("reveal_secret works, mocking 3", {
mockery::stub(where = reveal_secret, what = "ask", how = NULL)
expect_error(reveal_secret("top-secret"), "needed")
})
I hope this helps a bit?