如何使用phpunit在功能测试中使symfony显示异常

Fre*_*man 3 phpunit symfony

当我在控制台中使用 PhpUnit 运行单元测试时,所有异常都会立即显示在那里。然而,当我转向功能测试时,我看不到发生的异常。

首先,我尝试了 symfony,WebTestCase就像这里所说的那样。所以我$client用所需的参数打电话,我得到了回应。但是我花了一些时间才明白这种行为就像我手动打开要测试的页面一样。来自$client->request包含文本 (html)的响应。是的,那里显示了错误,但有很多 html,而且很难找到异常。是的,我可以使用,$crawler->filter('.text-exception')->first()->text()但我希望异常在单元测试中可见。当我测试命令时,PhpUnit 和正常情况一样显示异常。

我试图将代码复制web/app_dev.php到测试用例。但它是一样的。我只有 html 响应。

那么如何才能让 PhpUnit 在功能测试中像单元测试一样显示异常呢?

Ale*_*ons 5

您可以使用探查器来做到这一点:

$client->enableProfiler();
$client->request('GET', '/');
$profile = $client->getProfile();
$exceptionProfile = $profile->getCollector('exception');

if ($exceptionProfile->hasException()) {
    $message = sprintf(
        "No exception was expected but got '%s' with message '%s'. Trace:\n%s",
        get_class($exceptionProfile->getException()),
        $exceptionProfile->getMessage(),
        $exceptionProfile->getException()->getTraceAsString()
    );
    throw new AssertionFailedError($message);
}
Run Code Online (Sandbox Code Playgroud)