Consider the function:
root <- function(x) {
if(x < 0) {
cat("You cannot compute root of such numbers\n")
print(x)
stop("Root of negative number")
}
sqrt(x)
}
What is the best way to test the error behavior in such a function?
- If I do
tinytest::expect_error(root(-2)) the test passes but I also get output on screen. I'd like the tests to run with no clutter.
- If I test output
tinytest::expect_output(root(-2)) I get an error
- If I wrap error in output
tinytest::expect_stdout(tinytest::expect_error(root(-2))) I am not quite sure what I am testing, the test still passes if I remove stop.
While I can easily put the value inside the error message in this example, it may be more tricky with complex object with multi-line printout. Is it considered a good habit that complete output of error message should be spit out by stop itself, and not complemented with ordinary printing?
Thoughts/suggestions?
Consider the function:
What is the best way to test the error behavior in such a function?
tinytest::expect_error(root(-2))the test passes but I also get output on screen. I'd like the tests to run with no clutter.tinytest::expect_output(root(-2))I get an errortinytest::expect_stdout(tinytest::expect_error(root(-2)))I am not quite sure what I am testing, the test still passes if I removestop.While I can easily put the value inside the error message in this example, it may be more tricky with complex object with multi-line printout. Is it considered a good habit that complete output of error message should be spit out by
stopitself, and not complemented with ordinary printing?Thoughts/suggestions?