Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

echo in phpunit tests [duplicate]

Tags:

php

phpunit

I have been trying to echo stuff in my phpunit tests but no luck so far.

I read the documentation about the xml config file and apparently the debug parameter is what I am looking for. Unfortunately it still doesn't work. Anyhow here is my xml config file:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true"
         processIsolation="true"
         verbose="true"
         debug="true">
</phpunit> 

Both processIsolation and verbose are accepted but debug is not.

The command actually works pretty fine when I directly pass it to phpunit like this:

phpunit --debug MyTest.php # here stuff is echoed correctly

but with the xml config file it looks like it is ignored.

like image 718
nourdine Avatar asked Jan 09 '12 14:01

nourdine


3 Answers

Current versions of PHPUnit >3.6.4 (and all 3.5.* versions) will just print everything you echo in a test case.

<?php

class OutputTestCase extends PHPUnit_Framework_TestCase {

    public function testEcho() {
        echo "Hi";
    }   
}

produces:

phpunit foo.php 
PHPUnit 3.6.7 by Sebastian Bergmann.

.Hi

Time: 0 seconds, Memory: 3.25Mb

OK (1 test, 0 assertions)

So if you are on an old 3.6 version just upgrade :)

like image 93
edorian Avatar answered Nov 01 '22 06:11

edorian


Make sure you don't call exit() or kill(). PHPUnit buffers the echo statements and that buffer will be lost with no output if your script exits during the test.

like image 3
Michael Morris Avatar answered Nov 01 '22 06:11

Michael Morris


In case your test takes a long time and you would like to see the output during the process, add the following method to your test class:

protected function prontoPrint($whatever = 'I am printed!')
{
    // if output buffer has not started yet
    if (ob_get_level() == 0) {
        // current buffer existence
        $hasBuffer = false;
        // start the buffer
        ob_start();
    } else {
        // current buffer existence
        $hasBuffer = true;
    }

    // echo to output
    echo $whatever;

    // flush current buffer to output stream
    ob_flush();
    flush();
    ob_end_flush();

    // if there were a buffer before this method was called
    //      in my version of PHPUNIT it has its own buffer running
    if ($hasBuffer) {
        // start the output buffer again
        ob_start();
    }
}

Now whenever you call $this->prontoPrint($variable) inside your test class, it will immediately show the text in the console. I used this php.net comment to write the function.

PHPUnit 5.7.21 PHP 5.6.31 with Xdebug 2.5.5

like image 2
hpaknia Avatar answered Nov 01 '22 05:11

hpaknia