I am developing an R package and one of the function implements interaction with users through standard input via readline
. I now wonder how to test the behavior of this function, preferably with testthat
library.
It seems test_that
function assumes the answer is ""
for user-input. I wish I could test the behavior conditional of various answers users may type in.
Below is a small example code. In the actual development, the marryme
function is defined in a separate file and exported to the namespace.
devtools::test()
gets me an error on the last line because the answer never becomes yes. I would like to test if the function correctly returns true when user types "y"
.
library(testthat)
test_that("input", {
marryme <- function() {
ans <- readline("will you marry me? (y/n) > ")
return(ans == "y")
}
expect_false(marryme()) # this is good
expect_true(marryme()) # this is no good
})
marryme
into two functions. Put everything exceptreadline
in a function you can test and call that function with a wrapper function that containsreadline
. Btw., I'm not a fan of usingreadline
for user input. – Playletreadline
? – Toogood