【问题标题】:Failed asserting the HTTP status code is 200 not 500未能断言 HTTP 状态代码是 200 而不是 500
【发布时间】:2013-10-25 22:07:44
【问题描述】:

我正在尝试功能测试某个请求的 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 匹配失败。

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

那么这里出了什么问题?

【问题讨论】:

    标签: php unit-testing symfony functional-testing


    【解决方案1】:

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

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

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

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

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

    然后打印$error

    【讨论】:

    • 嗯,但是div.text_exception > h1 是什么?
    • @RafaelAdel xpath 到消息本身。更新了我的答案
    • 嗯,我试过了,但我没有打印回来。我认为if($block->count()) 返回错误。因为我已经在 if 声明中放置了 $this->assertEquals("dummy", $error)
    • 好的,我找到了,它是 text-exception 而不是 text_exception
    • @RafaelAdel 可能取决于框架版本
    【解决方案2】:

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

    echo $crawler->html();
    

    【讨论】:

      猜你喜欢
      • 2016-10-24
      • 2018-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-29
      • 2021-10-23
      相关资源
      最近更新 更多