Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log from within PHPUnit test case?

What is best practice for printing log statements from a PHPUnit test case?

I am running selenium test cases and want to print out something like "Log in acccomplished", "Page XY opened".

I want to see those in any log file I want. Would be good, if you can define a log level.

like image 505
Chris Avatar asked May 18 '26 04:05

Chris


2 Answers

I would suggest that You use the Selenium Server Logging. It will provide You with all debugging information You might need.

If it's not an option for You and You still want to log from the PHPUnit test cases, You have 3 options:

  1. Use the built-in logging functionality (documentation), which can be configured through either phpunit.xml file or the command line arguments (documentation);
  2. Create Your own logger by implementing the PHPUnit_Framework_TestListener interface, which is kind of limited because it supports only a limited amount of events You can log, such as startTest, endTest, addError, addFailure, etc. See the (documentation) for the complete list of the supported events. You could possibly add some more events to your implementation but that would also require that You override the PHPUnit_Framework_TestSuite::run() method by subclassing the PHPUnit_Extensions_TestDecorator class (documentation) or by implementing the PHPUnit_Framework_Test interface (documentation).
  3. The easiest and more flexible option is to subclass the PHPUnit_Framework_TestCase class and implement the logging functionality there. This will allow You to log from within Your test methods.(documentation)
like image 125
zafarkhaja Avatar answered May 19 '26 17:05

zafarkhaja


You can implement a test listener, specify it in your phpunit.xml.dist, and do whatever you want, with whatever logging system you want (Monolog is popular) See the documentation for a better writeup and example than I can write off the top of my head.

If you want to specify messages in the test methods, you could have your tests inherit from a common class that adds a log method. And do whatever you want in there. I don't like that as a solution, but it's certainly an option.

like image 33
jdd Avatar answered May 19 '26 17:05

jdd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!