SymfonyWorld Online 2021 Winter Edition December 9 – 10, 2021 100% Online +20 talks and workshops

New in Symfony 5.2: Form testing asserts

Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.

Contributed by
Matthieu Napoli
in #38288 and #38287.

Testing is an essential part of Symfony applications. That’s why we promote testing in the docs and provide specific testing utilities like the PhpUnit bridge. In Symfony 5.2 we’ve improved our list of custom test asserts with new asserts for the Symfony Forms.

In previous Symfony versions, testing Symfony forms required you to deal with the form view variables and do things like this:

1
2
3
4
$view = $this->factory->create(TestedType::class, $formData)->createView();

$this->assertArrayHasKey('custom_var', $view->vars);
$this->assertSame('expected value', $view->vars['custom_var']);

Now you can use the assertFormValue() and assertCheckboxChecked() methods to check form values without dealing with low-level details like the view variables:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
namespace App\Tests\Controller;

use App\Entity\Post;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class SomeTest extends WebTestCase
{
    public function testIndex(): void
    {
        $client = static::createClient();
        $crawler = $client->request('GET', '/some-page');

        $client->submitForm('Save', [
            'activateMembership' => 'on',
            'trialPeriod' => '7',
        ]);

        self::assertFormValue('#form', 'trialPeriod', '7');
        self::assertCheckboxChecked('activateMembership');
    }
}
Help the Symfony project!

As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.

Comments

Should be "self::assertFormValue(...)" and "self::assertCheckboxChecked(...)"
Thank you for this improvement 🙂 Is there any reason to accept the form identifier ('#form') in assertFormValue but not in assertCheckboxChecked ?
@Massimiliano you are right. It's fixed now. Thanks!

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.