How to view notifications during testing?

I have a class that gives a non-fatal notification:

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

Here's the basic unit test:

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

Naturally, PHPUnit converts this notification into an exception, which does not necessarily throw a test as an error.

1 error occurred:

1) MyClassTest :: testCanFoo
Pay attention to this post.

First, let me point out that I like that I can read this notice, and this one is what I want , but without verification.

I know that I can pass the test with 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 notification is completely absorbed.

PHPUnit 5.5.4 by Sebastian Bergman and contributors.

. 1/1 (100%)

Time: 17 ms, memory: 4.00 MB

OK (1 test, 1 statement)

?

+4
2

:

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());
    }
}
+2

Netsilik/BaseTestCase ( MIT), /, .

Waring/Notice, :

composer require netsilik/base-test-case


E_USER_NOTICE:

<?php
namespace Tests;

class MyTestCase extends \Netsilik\Testing\BaseTestCase
{
    /**
     * {@inheritDoc}
     */
    public function __construct($name = null, array $data = [], $dataName = '')
    {
        parent::__construct($name, $data, $dataName);

        $this->_convertNoticesToExceptions  = false;
        $this->_convertWarningsToExceptions = false;
        $this->_convertErrorsToExceptions   = true;
    }

    public function test_whenNoticeTriggered_weCanTestForIt()
    {
        $foo = new Foo();
        $foo->bar();

        self::assertErrorTriggered(E_USER_NOTICE, 'The notice string');
    }
}

.

0

Source: https://habr.com/ru/post/1654833/


All Articles