The following example comes from the official documentation:
use AppBundle\Form\Type\TestedType;
use AppBundle\Model\TestObject;
use Symfony\Component\Form\Test\TypeTestCase;
class TestedTypeTest extends TypeTestCase
{
public function testSubmitValidData()
{
$formData = array(
'test' => 'test',
'test2' => 'test2',
);
$form = $this->factory->create(TestedType::class);
$object = TestObject::fromArray($formData);
// submit the data to the form directly
$form->submit($formData);
$this->assertTrue($form->isSynchronized());
$this->assertEquals($object, $form->getData());
$view = $form->createView();
$children = $view->children;
foreach (array_keys($formData) as $key) {
$this->assertArrayHasKey($key, $children);
}
}
}
However, with a real unit testing approach, the test should only contain an individual class as a SUT, everything else should be Test Doubles like stubs, mock objects...
How should we unit test a Symfony form using Test Doubles like mock objects?
We could assume a simple form class:
class TestedType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('firstname', TextType::class, [
'label' => 'First name',
'attr' => [
'placeholder' => 'John Doe',
],
])
}
}