我正在测试一个symfony应用。
断言失败时,我想查看Web客户端HTML输出。 我正在寻找一个简短而优雅的版本:
if(1 !== $crawler->filter('.flash-success')->count())
file_put_contents("debug.html", $this->client->getResponse()->getContent());
$this->assertEquals(1, $crawler->filter('.flash-success')->count());
我的建议是注册一个获取assertXXX
的第三个参数的回调:
// ideally like this
phpunit_register_callback(write_to_disk_callback);
$this->assertEquals(1, $crawler->filter('.flash-success')->count(), $this->client->getResponse()->getContent());
在我的情况下,回调应该将消息写入磁盘上的文件,因此我可以使用浏览器将其打开...
function write_to_disk_callback($message){
file_put_contents("debug.html", $message);
}
答案 0 :(得分:2)
我认为应该看看phpunit listeners
这是一个如何在SF项目中实现侦听器的小例子
首先,您必须创建一个侦听器:
<?php
namespace Tests\PHPUnit;
use PHPUnit\Framework\AssertionFailedError;
use PHPUnit\Framework\Test;
use PHPUnit\Framework\TestListener;
use PHPUnit\Framework\TestListenerDefaultImplementation;
use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class SimpleTestListener implements TestListener
{
use TestListenerDefaultImplementation;
public function addFailure(Test $test, AssertionFailedError $e, float $time): void
{
if ($test instanceof WebTestCase && method_exists($test, 'getClient')) {
/** @var Client $client */
$client = $test->getClient();
// Write the client response to a file
}
}
}
然后,在您的phpunit.xml上添加侦听器:
<listeners>
...
<listener class="Tests\PHPUnit\SimpleTestListener"/>
</listeners>
最后,更新您的测试文件:
<?php
namespace Tests\PHPUnit\YesWeHack;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class MyTest extends WebTestCase
{
static private $client;
static public function getClient()
{
return static::$client;
}
protected static function createClient(array $options = [], array $server = [])
{
static::$client = parent::createClient($options, $server);
return static::$client;
}
public function testReportIsFixed()
{
$client = static::createClient();
$client->request('GET', '/');
$this->assertEquals(500, $client->getResponse()->getStatusCode());
}
}
请注意,MyTest
类仅是示例,不应那样使用,它仅是示例。
至少您应该适当地将statics属性和方法移动到测试将扩展的抽象类。
这是在一个项目上进行的简单测试的结果,在该项目中,我将响应代码和响应内容转储到了侦听器中:
PHPUnit 7.5.8 by Sebastian Bergmann and contributors.
Testing Project Test Suite
int(200)
string(523) "<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
<div class="form">
<form name="form" method="post">
<div><label for="form_username" class="required">Username</label><input type="text" id="form_username" name="form[username]" required="required" /></div>
<input type="hidden" id="form__token" name="form[_token]" value="2AsriLX8VMS0VqomR2wtTGk159TXMhYQJlPt_Chwtv8" />
</form>
</div>
</body>
</html>
"
F 1 / 1 (100%)
Time: 118 ms, Memory: 16.00 MB
There was 1 failure:
1) Tests\PHPUnit\YesWeHack\YWH_PGM5_1Test::testReportIsFixed
Failed asserting that 200 matches expected 500.
MyTest.php:29
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.