断言 HTTP 状态代码失败是 200 而不是 500


Failed asserting the HTTP status code is 200 not 500

我正在尝试功能测试某个请求的HTTP状态代码是否200 500。我正在使用Symfony2,这是代码:

public function testIndex()
{
    $client = static::createClient();
    $crawler = $client->request('GET', "/");
    $this->assertEquals('Ibw'JobeetBundle'Controller'JobController::indexAction', $client->getRequest()->attributes->get('_controller'));
    $this->assertEquals(200 , $client->getResponse()->getStatusCode());
    $this->assertEquals(0, $crawler->filter('.jobs td.position:contains("Expired")')->count());
}

结果是:

1) Ibw''JobeetBundle''Tests''Functional''JobControllerTest::testIndex 未能断言 500 个匹配项预期为 200 个。

当我通过浏览器手动访问路由"/"时,它工作得很好。

那么这里有什么问题呢?

500 错误可能是由您的任何情况引起的。

在这种情况下,你可以做的是转储响应的内容并检查Symfony调试消息。

我通常使用这样的代码片段直接在终端中快速检查此类错误:

if (!$response->isSuccessful()) {
    $block = $crawler->filter('div.text_exception > h1');
    if ($block->count()) {
        $error = $block->text();
    }
}

其中div.text_exception > h1是从 Symfony2 调试页面到消息本身的 xpath

然后只需打印$error

您也可以在请求后回显 html,以查看响应中的内容。

echo $crawler->html();