test the return value of a method that triggers an error with PHPUnit

前端 未结 5 1616
自闭症患者
自闭症患者 2020-12-16 17:33

This question is specific to using PHPUnit.

PHPUnit automatically converts php errors to exceptions. Is there a way to test the return value of a method that

5条回答
  •  被撕碎了的回忆
    2020-12-16 17:58

    Instead of expecting a generic "Exception", what about expecting a "PHPUnit_Framework_Error" ?

    Something like this might do :

    /**
     * @expectedException PHPUnit_Framework_Error
     */
    public function testFailingInclude()
    {
        include 'not_existing_file.php';
    }
    

    Which, I suppose, might also be written as :

    public function testLoadFile ()
    {
        $this->setExpectedException('PHPUnit_Framework_Error');
        $result = load_file('/some/non-existent/file');
    
        // code after this point never gets executed
    
        $this->assertFalse($result);
    }
    

    For more informations, see Testing PHP Errors
    Especially, it says (quoting) :

    PHPUnit_Framework_Error_Notice and PHPUnit_Framework_Error_Warning represent PHP notices and warning, respectively.


    Looking at the /usr/share/php/PHPUnit/TextUI/TestRunner.php file I have on my system, I see this (line 198 and following) :

    if (!$arguments['convertNoticesToExceptions']) {
        PHPUnit_Framework_Error_Notice::$enabled = FALSE;
    }
    
    if (!$arguments['convertWarningsToExceptions']) {
        PHPUnit_Framework_Error_Warning::$enabled = FALSE;
    }
    

    So maybe you'll have to pass some kind of parameter to activate that behaviour ? But it seems to be enabled by default...

提交回复
热议问题