2017-07-27 172 views
0

寻找一些帮助来编写更好的代码/测试,但似乎马上就发现了一个问题 - 任何帮助将不胜感激。PHPUnit没有捕捉异常

脚本:

$feed = 'App\Http\Services\Supplier\Feeds\\' . ucwords($feedName) . "Feed"; 

if (class_exists($feed)) { 
    return new $feed($headerRowToSkip); 
} else { 
    throw new Exception("Invalid feed type given."); 
} 

测试:

public function testBuild() 
{ 
    SupplierFeedFactory::build('MusicMagpie', 1); 
    $this->expectExceptionMessage("Invalid feed type given."); 
} 

错误:

有1次失败:

1)测试\功能\帐户\供应商\饲料\ SupplierFeedFactoryTest :: testBuild 无法断言“异常”类型的异常是抛出。

+0

期望值必须在测试代码之前表达。否则,它们是无用的。就好像你在雨停后买伞一样。在你的情况下,调用'$ this-> expectExceptionMessage()'的行不会运行,因为测试的代码('SupplierFeedFactory :: build()')已经抛出了异常。 – axiac

回答

1

PHPUnit方法是字面的,EXPECTexception所以你所要做的就是在异常发生之前把它放好。

public function testBuild() 
{ 
    $this->expectException('Exception'); 
    $this->expectExceptionMessage("Invalid feed type given."); 
    SupplierFeedFactory::build('MusicMagpie', 1); 
} 
+0

您也可以使用注解,https://phpunit.de/manual/current/en/writing-tests-for-phpunit.html和其他示例,例如网站上的问答:https:// stackoverflow.com/a/39837176/367456 – hakre