echo in phpunit tests [duplicate]

心不动则不痛 提交于 2019-12-21 03:53:30

问题


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.


回答1:


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 :)




回答2:


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.




回答3:


processIsolation is suppressing the output of tests so you have to disable it. The interaction with the debug flag was probably an oversight introduced with this: https://github.com/sebastianbergmann/phpunit/pull/1489




回答4:


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



来源:https://stackoverflow.com/questions/8790271/echo-in-phpunit-tests

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!