在phpunit测试中调用file_put_contents时会引发异常。为什么?

时间:2018-11-04 13:16:48

标签: php phpunit

根据docs,当出现错误时,file_put_contents返回false。但是,当我在单元测试中使用以下代码(实际上是在我尝试测试的代码中,这只是一个简单的示例)时,它引发了异常,而不仅仅是返回false:

class MyTest extends \PHPUnit\Framework\TestCase
{
    public function testSomething()
    {
        $result = file_put_contents('/test.txt', 'bla');
        if (false === $result) {
            echo "this went wrong!";
        }
    }
}

这将显示以下内容:

PHPUnit 7.0.2 by Sebastian Bergmann and contributors.

E                                                                   1 / 1 (100%)

Time: 79 ms, Memory: 12.00MB

There was 1 error:

1) MyTest::testSomething
file_put_contents(/test.txt): failed to open stream: Permission denied

/home/luc/public_html/vereniging/vendor/symfony/phpunit-bridge/DeprecationErrorHandler.php:108
/home/luc/public_html/vereniging/src/Core/SerialLetterBundle/Tests/Services/test.php:7

ERRORS!
Tests: 1, Assertions: 0, Errors: 1.

在假设抛出异常的情况下,我将代码更改为

class MyTest extends \PHPUnit\Framework\TestCase
{
    public function testSomething()
    {
        try {
            file_put_contents('/test.txt', 'bla');
        } catch (\Exception $e) {
            echo "\nThis is an exception: ".$e->getMessage();
        }
    }
}

现在将显示以下内容:

PHPUnit 7.0.2 by Sebastian Bergmann and contributors.

R                                                                   1 / 1 (100%)
This is an exception: file_put_contents(/test.txt): failed to open stream: Permission denied

Time: 86 ms, Memory: 12.00MB

There was 1 risky test:

1) MyTest::testSomething
This test did not perform any assertions

OK, but incomplete, skipped, or risky tests!
Tests: 1, Assertions: 0, Risky: 1.

任何人都可以向我解释一下,为什么phpunit调用file_put_contents时会表现出不同的行为,以及如何测试评估返回值为false的代码?我正在使用php 7.2.5,如果这很重要。

0 个答案:

没有答案