【问题标题】:Object of class Symfony\Component\DomCrawler\Crawler could not be converted to stringSymfony\Component\DomCrawler\Crawler 类的对象无法转换为字符串
【发布时间】:2014-08-06 03:53:56
【问题描述】:

我正在尝试使用 DemoController 在 Symfony2 中运行我的第一个功能测试。

如果我从浏览器加载页面,则显示的数据是正确的。 但是,如果我尝试使用命令 phpunit -c app 运行测试,则会收到以下错误消息:

There was 1 error:

1) Blog\CoreBundle\Tests\Controller\AuthorControllerTest::testShow
Object of class Symfony\Component\DomCrawler\Crawler could not be converted to string

这是我的 AuthorControllerTest 类:

<?php

namespace Blog\CoreBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

/**
 * Class AuthorControllerTest
 */
class AuthorControllerTest extends WebTestCase
{
    /**
     * Test show author
     */
    public function testShow()
    {
        $client = static::createClient();

        /** @var Author $author */
        $author = $client->getContainer()
            ->get('doctrine')
            ->getManager()
            ->getRepository('ModelBundle:Author')
            ->findFirst();
        $authorPostCount = $author->getPosts()->count();

        $crawler = $client->request('GET', '/author/'.$author->getSlug());

        $this->assertTrue($client->getResponse()->isSuccessful(), 'The response was not successful');

        $this->assertTrue($authorPostCount, $crawler->filter('h2'), 'There should be '.$authorPostCount.' posts');
    }

}

【问题讨论】:

    标签: symfony symfony-2.1


    【解决方案1】:

    当您执行以下行时,您会收到消息错误:

    $this->assertTrue($authorPostCount, $crawler->filter('h2'), 'There should be '.$authorPostCount.' posts');
    

    错误是由于您传递给 assertTrue 函数的参数错误。这仅用于断言条件为真。

    要断言元素的数量,您应该使用函数 assertCount。

    $this->assertcount($authorPostCount, $crawler->filter('h2'), 'There should be '.$authorPostCount.' posts');
    

    【讨论】:

      【解决方案2】:

      $crawler-&gt;filter('h2') 返回一个对象。要比较它的内容,请使用text() 方法提取信息。试试

      $this->assertEquals($authorPostCount, $crawler->filter('h2')->text(), 'There should be '.$authorPostCount.' posts');
      

      编辑:

      如果您只想比较帖子数量(不是&lt;h2&gt; 节点值,而是页面上&lt;h2&gt; 节点的数量),请使用count()

      $this->assertEquals($authorPostCount, $crawler->filter('h2')->count(), 'There should be '.$authorPostCount.' posts');
      

      或者只是

      $this->assertCount($authorPostCount, $crawler->filter('h2'), 'There should be '.$authorPostCount.' posts');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-05
        • 2015-07-27
        相关资源
        最近更新 更多