Contributed by Alex Rock and Fabien Potencier in #30813.
In Symfony applications, creating functional tests is simple thanks to the
utilities provided by the WebTestCase
class and PHPUnit's assertions.
However, for common use cases (such as testing that the response was successful
or that it redirected to some URL) the assert___()
methods are too basic
and require writing too much code.
Lots of Symfony developers have created their own utility classes for tests to
solve this issue. That's why in Symfony 4.3 we've decided to add the most common
ones in a new Symfony\Bundle\FrameworkBundle\Test\WebTestAssertions
trait
which is included by default in WebTestCase
, so you only have to upgrade
your application to Symfony 4.3 to start using them.
Example of checking if the response was successful:
1 2 3 4 | // Before
$this->assertSame(200, $client->getResponse()->getStatusCode());
// After
$this->assertResponseIsSuccessful();
|
Example of checking if the response redirects to some URL:
1 2 3 4 5 | // Before
$this->assertSame(301, $client->getResponse()->getStatusCode());
$this->assertSame('https://example.com', $client->getResponse()->headers->get('Location'));
// After
$this->assertResponseRedirects('https://example.com', 301);
|
Example of checking if some element contains some text:
1 2 3 4 | // Before
$this->assertContains('Hello World', $crawler->filter('h1')->text());
// After
$this->assertSelectorTextContains('h1', 'Hello World');
|
The new assertions will make your tests more readable and will boost your productivity. Here's the full list of assertions available:
assertClientCookieValueEquals()
assertClientHasCookie()
assertClientNotHasCookie()
assertClientRawCookieValueEquals()
assertHttpCodeEquals()
assertInputValueEquals()
assertInputValueNotEquals()
assertPageTitleContains()
assertPageTitleEquals()
assertRequestAttributeValueEquals()
assertResponseCookieValueEquals()
assertResponseCookieValueNotEquals()
assertResponseHasCookie()
assertResponseHasHeader()
assertResponseHeaderEquals()
assertResponseHeaderNotEquals()
assertResponseIsSuccessful()
assertResponseNotHasCookie()
assertResponseNotHasHeader()
assertResponseRedirects()
assertRouteEquals()
assertSelectorContainsText()
assertSelectorExists()
assertSelectorNotContainsText()
assertSelectorNotExists()
What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...