Exception handling PHPUnit未捕获异常

Exception handling PHPUnit未捕获异常,exception-handling,phpunit,Exception Handling,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

正在寻找一些帮助来编写更好的代码/测试,但似乎马上就遇到了一个问题-任何帮助都将不胜感激

脚本:

$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.");
}
测试:

错误:

有1次失败:

1) Tests\Feature\Account\Supplier\Feeds\SupplierFeedFactoryTest::testBuild
断言抛出“exception”类型的异常失败。

PHPUnit方法是literal,EXPECTexception,因此您所要做的就是在异常实际发生之前将其放入

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

您也可以为此使用注释,请参见:和其他示例,如网站上的Q&A:@LeeJ无需添加
$this->expectException('Exception')要测试异常消息,有一个关于它的填充,现在已经解决了。在测试代码之前必须表达期望。否则,它们是无用的。就像雨停后你在买伞一样。在您的情况下,调用
$this->expectExceptionMessage()
的行没有运行,因为(还有什么?)测试代码(
SupplierFeedFactory::build()
)引发了异常。
public function testBuild()
{
    $this->expectException('Exception');
    $this->expectExceptionMessage("Invalid feed type given.");
    SupplierFeedFactory::build('MusicMagpie', 1);
}