我正在尝试使用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');
}
}
答案 0 :(得分:2)
执行以下行时收到消息错误:
$this->assertTrue($authorPostCount, $crawler->filter('h2'), 'There should be '.$authorPostCount.' posts');
错误是由于您传递给assertTrue函数的错误参数引起的。这仅用于断言条件为真。
要断言你应该使用函数assertCount的元素数量。
$this->assertcount($authorPostCount, $crawler->filter('h2'), 'There should be '.$authorPostCount.' posts');
答案 1 :(得分:1)
$crawler->filter('h2')
返回一个对象。要比较它的内容,请使用text()
方法提取信息。尝试
$this->assertEquals($authorPostCount, $crawler->filter('h2')->text(), 'There should be '.$authorPostCount.' posts');
修改强>
如果您只是想比较帖子数量(不是<h2>
节点值,而是页面上<h2>
个节点的数量),请使用count()
$this->assertEquals($authorPostCount, $crawler->filter('h2')->count(), 'There should be '.$authorPostCount.' posts');
或只是
$this->assertCount($authorPostCount, $crawler->filter('h2'), 'There should be '.$authorPostCount.' posts');