2017-05-18 11 views
0

我试图在我的代码中测试异常。File_get_contents当文件不存在时不计算为false

public function testGetFileThrowsException(){ 
    $this->expectException(FileNotFoundException::class); 
    $file = "db.json"; 
    $this->review->getData($file); 
} 

“db.json”文件不存在。我的目标是tp有getData()文件来抛出FileNotFoundException。这里是的getData()代码:

public function getData($path){ 

    if(file_get_contents($path) === false){ 
     throw new FileNotFoundException; 
    } 
    return $file; 
} 

的问题是,而不是评估为False,抛出异常,的file_get_contents函数返回:

1) CompanyReviewTest::testGetFileThrowsException 
file_get_contents(db.json): failed to open stream: No such file or directory 

所以测试没有成功运行。任何想法为什么会发生这种情况?

+0

___有一点:___'$ file'在该方法中不存在?但是如果你将它编码为'if($ file = file_get_contents($ path)=== false){' – RiggsFolly

+0

1)在调试的时候请记住打开错误报告。 2)如果出现错误报告,请检查错误日志。 – RiggsFolly

+0

感谢关于$文件的提示。不幸的是,我的目标是测试如果$ path不存在时是否抛出异常。 –

回答

1

file_get_contents()产生E_WARNING级别错误(无法打开流),这是你想要压制的,因为你已经用异常类处理它了。

您可以通过在file_get_contents()前面添加PHP's error control operator@,例如禁止这种警告:以上

<?php 

$path = 'test.php'; 
if (@file_get_contents($path) === false) { 
    echo 'false'; 
    die(); 
} 

echo 'true'; 

?> 

呼应假的,没有@操作返回两个E_WARNING和呼应假。警告错误可能会干扰您的抛出函数,但没有看到代码,因此很难说。

+0

但它使用'@'错误抑制器___很少____ – RiggsFolly

0

你有2个解决穷人一个是隐藏的错误一样,

public function getData($path){ 

    if(@file_get_contents($path) === false){ 
     throw new FileNotFoundException; 
    } 
    return $file; 
} 

或检查也许,如果该文件存在(更好的解决办法我猜)

public function getData($path){ 

if(file_exists($path) === false){ 
    throw new FileNotFoundException; 
} 
return $file; 
} 
相关问题