testing functions that print messages

testthat
unit-testing

#1

I am trying to run some unit testing with testthat. The standard output is something like:

> devtools::test()
Loading packagex
Testing packagex
✔ | OK F W S | Context
✔ |  1       | test 1 [3.5 s]
✔ |  9       | test 2 [0.6 s]
✔ |  4       | test 3

However, if the function prints any messages, those will show up in the output, making it mostly unreadable. Is there a way of getting around that?


#2

Take a look at family of functions in testthat that deal with side-effects (output to console is a side-effect), e.g., expect_output, expect_message, expect_error and so on. This should provide functionality you need.


#3

From what I understand, those will test if the output/message/warning/error is generated. Those will properly treat the output. However, the output will still mess up the other tests.


#4

What method is being used to generate the output? cat() or message()? More often than not, one should be using message(), which is naturally absorbed by testthat, instead of cat().

What @mishabalyasin says is basically the answer though. All of those expect_output()-type of functions absorb a specific type of output and, optionally, test something about it. You can use them without specifying the regexp.


#5

Great question. I am using message() for output, but some of the functions I call within my functions do not. Upon closer examination, it appears that it is only the other output that shows up. What should I do about that?


#6

I would use expect_output() or capture_output() as a diaper in that case, depending on whether I wanted to test the output or just absorb it.