Answer the question
In order to leave comments, you need to log in
How to properly test entity validation?
Good evening! In the process of mastering unit testing, I came to testing entities and forms. The documentation clearly states that it is not necessary to test the validation in the form, it is necessary to do it directly for the constraints. ( symfony.com/doc/current/form/unit_testing.html).
I wrote such a test, it worked great: test-> test cases-> red strip-> code-> green strip.
<?php
namespace App\Tests\Controller\Admin;
use App\Entity\MyEntity;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\Validation;
/**
* @group unit
*/
class MyEntityValidationTest extends TestCase
{
/**
* @dataProvider getMyEntityInvalidData
*/
public function testMyEntityIsInvalid($name, $description)
{
$validator = Validation::createValidatorBuilder()->enableAnnotationMapping()->getValidator();
$myEntity = new MyEntity();
$myEntity->setName($name);
$myEntity->setDescription($description);
/** @var ConstraintViolation[] $violations */
$violations = $validator->validate($myEntity);
$this->assertTrue(count($violations) == 1);
}
public function getMyEntityInvalidData()
{
// empty name
yield ['name' => null, 'description' => 'valid description'];
// invalid name length
yield ['name' => '1', 'description' => 'valid description'];
//invalid name length
yield [
'name' => 'qwjdhfnvjcnfhvn nvhf chfn ndnwb nvbchf r nfnefhvn nvjdhf2',
'description' => 'valid description',
];
}
Answer the question
In order to leave comments, you need to log in
This is not unit testing, but integration testing. But forms are much easier to test with functional tests .
An example of working with the form can be seen in the demo application: https://github.com/symfony/demo/blob/96cab4e312a76...
But validation is not tested there. Generally speaking, you are the first person in my memory who does such tests :)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question