New in Symfony 6.4: More Testing Assertions


Symfony provides custom assertions to simplify your tests. They are optional,
but we recommend to use them to make your tests easier to maintain. For example:

// with default PHPUnit assertions
$this->assertSame(
'This is not a valid coupon code.',
trim($crawler->filter('#errorMessages')->text())
);

// with custom Symfony assertions
$this->assertSelectorTextContains('#errorMessages', 'This is not a valid coupon code.');

In Symfony 6.4 we're introducing new custom assertions.

Any Selector Assertions

Contributed by Samaƫl Villette
in #50306.

Consider the following HTML code:

<ul>
<li>test 1li>
<li>test 2li>
<li>test 3li>
ul>

If you need to test that any of the

  • items contains the text test 3,
    you need to loop over all
  • elements or extract all their contents:

    $nodes = $crawler->filter('ul li')->each(fn(Crawler $node) => $node->text());
    $this->assertContains('test3', $nodes);

    In Symfony 6.4, you can use the new assertions:

    $this->assertAnySelectorTextSame('ul li', 'test 3');
    $this->assertAnySelectorTextContains('ul li', 'test');

    HttpClient Assertions

    Contributed by Mathieu Santostefano
    in #50662.

    Symfony 6.4 also adds a few assertions to ensure that certain HTTP calls were
    triggered (via the HttpClient component) during the application execution:

    // method arguments: (string) URL, (string) method, (string|array) body, (array) $headers, (string) http_client ID
    $this->assertHttpClientRequest('https://example.com/', 'GET');
    $this->assertHttpClientRequest('https://example.com/upload', 'POST', ['foo' => 'bar']);

    // method arguments: (string) URL, (string) method, (string) http_client ID
    $this->assertNotHttpClientRequest('https://example.com/other');

    // method arguments: (int) count, (string) http_client ID
    $this->assertHttpClientRequestCount(2);

    Email Subject Assertions

    Contributed by Johan Vlaar
    in #50200.

    Symfony already provides many assertions related to the mailer, such as
    assertEmailCount(), assertEmailTextBodyContains(), assertEmailHasHeader(), etc.
    In Symfony 6.4 we're adding two new assertions related to the email subjects:

    $this->assertEmailSubjectContains($email, 'Your order was processed successfully');
    $this->assertEmailSubjectNotContains($email, 'Your order is pending');

    Sponsor the Symfony project.