PHPUnit – Integration Tests Console Output

When writing integration tests we have special group of slow tests that do a lot of stuff like performing hundreds of downloads or editing thousands of entries. In some cases one of the actions can trigger fatal error and the message would not be specific enough to determine which of those actions broke everything.

Here is a neat trick to enable any test to show console output, it uses fwrite to write to standard I/O stream:

1. First we’d have to create a trait somewhere where our traits live:

<?php

namespace Some\Namespace\Traits\Test;

trait ConsoleOutput {

    /**
     * Show console output.
     *
     * @param  string  $text
     *
     * @return void;
     */
    public function consoleLog($text)
    {
        fwrite(STDERR, $text."\n");
    }
}

2. Use this trait in our test case

3. From our tests we can now send output that is seen in terminal, so the more complicated tests can describe their actions.


$this->consoleLog("Hello world!");

As a possible enchantment, the trait method can add time stamp to each message, accept and dump an optional variable etc.

Leave a Reply

Your email address will not be published. Required fields are marked *