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

前端 未结 5 1599
自闭症患者
自闭症患者 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 18:07

    Actually there is a way to test both the return value and the exception thrown (in this case an error converted by PHPUnit).

    You just have to do the following:

    public function testLoadFileTriggersErrorWhenFileNotFound()
    {
        $this->assertFalse(@load_file('/some/non-existent/file'));
    
        $this->setExpectedException('PHPUnit_Framework_Error_Warning'); // Or whichever exception it is
        load_file('/some/non-existent/file');
    }
    

    Notice that to test for the return value you have to use the error suppression operator on the function call (the @ before the function name). This way no exception will be thrown and the execution will continue. You then have to set the expected exception as usual to test the error.

    What you cannot do is test multiple exceptions within a unit test.

提交回复
热议问题