Matthieu Napoli
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');
    }
}
Published in #Living on the edge