Jeff Puckett II Jeff Puckett II - 2 months ago 7
PHP Question

How to view notices when testing?

I have a class that issues a non-fatal notice:

class MyClass {
public function foo(){
trigger_error('Notice this message.', E_USER_NOTICE);
return true;
}
}


Here's a basic unit test:

class MyClassTest extends PHPUnit_Framework_TestCase {
public function testCanFoo(){
$obj = new MyClass;
$this->assertTrue($obj->foo());
}
}


Naturally PHPUnit converts this notice into an exception, which uncaught necessarily fails the test as an error.


There was 1 error:

1) MyClassTest::testCanFoo

Notice this message.


Firstly, let me point out that I love that I can read this notice, and this is what I want, but without failing the test.

I know I can get the test to pass with a docblock.

class MyClassTest extends PHPUnit_Framework_TestCase {
/**
* @expectedException PHPUnit_Framework_Error_Notice
*/
public function testCanFoo(){
$obj = new MyClass;
$this->assertTrue($obj->foo());
}
}


But now the notice is completely swallowed up.


PHPUnit 5.5.4 by Sebastian Bergmann and contributors.

. 1 / 1 (100%)

Time: 17 ms, Memory: 4.00MB

OK (1 test, 1 assertion)


How can I get it to both pass the test and view the notice message?

Answer

You can disable the conversion into exception in this manner:

class MyClassTest extends PHPUnit_Framework_TestCase {
    public function testCanFoo(){
        // disable conversion into exception
        PHPUnit_Framework_Error_Notice::$enabled = false;
        $obj = new MyClass;
        $this->assertTrue($obj->foo());
    }
}