Reputation: 1536
I'm trying to get starting the UnitTest process with symfony 3 and I'm still confused how to do that and how to test my forms, I've followed the official documentation and the instructions to create the TestClass :
TestFormType :
<?php
namespace Tests\EvalBundle\Form\Type;
use EvalBundle\Form\DepartmentType;
use EvalBundle\Entity\Department;
use Symfony\Component\Form\Test\TypeTestCase;
class DepartmentTypeTest extends TypeTestCase
{
public function testSubmitValidData(){
$formData = array(
'name' => 'test',
);
$departmentType = new DepartmentType();
$form = $this->factory->create($departmentType);
$department = new Department();
$department = fromArray($formData);
$form->submit($formData);
$this->assertTrue($form->isSynchronized());
$this->assertEquals($department, $form->getData());
$view = $form->createView();
$children = $view->children;
foreach (array_keys($formData) as $key) {
$this->assertArrayHasKey($key, $children);
}
}
}
?>
I've got some errors
that those functions :
fromArray,assertTrue,assertEquals,assertArrayHasKey : they are not undefined.
Is some one here familiar with this can help me to understand the concept?
Upvotes: 2
Views: 325
Reputation: 182
$this->factory->create(DepartmentType::class)
instead$departmentType = new DepartmentType();
$form = $this->factory->create($departmentType);
If problem still appears it could be cause by one of the following issue:
Method fromArray
is not exists in your code. I suggest to feed Department
object by setters like $department->setName('test');
. In Symfony3 documentation method fromArray
was mentioned but we should implement this method by ourselfs
assertTrue
, assertEquals
,assertArrayHasKey
- suggested that you are using incorrect TestTypeCase
class.
Below I pasted working unit test for form with fields email
and surname
<?php
namespace Tests\AppBundle\Form;
use Symfony\Component\Form\Test\TypeTestCase;
use AppBundle\Form\RecipientType;
use AppBundle\Entity\Recipient;
class RecipientTypeTest extends TypeTestCase
{
public function testAddRecipient()
{
$formData = array(
'email' => '[email protected]',
'surname' => 'Doe',
);
$form = $this->factory->create(RecipientType::class);
$object = new Recipient();
$object->setEmail($formData['email']);
$object->setSurname($formData['surname']);
// 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);
}
}
}
Upvotes: 1