I am trying to test a custom validator which use the entity manager.
The validator is working fine in the form, but I'm still having problem testing it: it never throw a violation.
My validator is a Class validator but add a violation to the field Lastname $this->context->addViolationAt('lastname',$message,$param);
There is the code in My Test Class:
public function testNoMoreThreeBatman() {
$validator = Validation::createValidatorBuilder()->getValidator();
//I have already checked I got my test database ok, full with what I want
//I create a new one with the name 'wayne' (so it'll be not valid)
$user = new User();
$user->setLastname('wayne');
$violationList = $validator->validate($user);
$this->assertEquals(1, $violationList->count());
}
I have found a lot of topics, but no one is giving me a hint. I have test with another custom validation, a simple one and I have no problem. I'm wondering if the problem could come from the fact it's a class validator or the fact it add the violation to a field
Because my answer is in a comment, I post the response here for more visibility:
Correct is Validation::createValidatorBuilder()->getValidator();
Instead of $validator = Validation::createValidatorBuilder()->getValidator();
So while its really a functional test, I think you best bet would be to just grab the validator service:
class MyTest extends Symfony\Bundle\FrameworkBundle\Test\WebTestCase
{
public function test()
{
$client = static::createClient();
$validator = $client->getContainer()->get('validator');
...
=============================================================
Can you explain the difference between calling static::get('validator') and Validation::createValidatorBuilder?
In answer to your comment, I don't know where the static:get you are referring to comes from. What base class are you using for your unit test? But it does not really matter because I assume that static::get is accessing the dependency injection container.
So your question is really: What is the difference between using the Symfony 2 container and the actual component itself?
The thing to understand is that when you start up a Symfony 2 app, all kinds of configuration files are read and all kind of things happen behind the scenes. In particular, a service called validator is created and initialized by things such as validation.yml. Likewise, your custom validator is created and is passed your entity manager as a dependency.
None of this happen when you just use Validation::createValidatorBuilder by itself. No configuration, no mapping, no entity managers etc. Take a look at the code to see what actually happens. Take a look at the component documentation to see how to use it directly. It's actually a worth while exercise to go through as it helps to understand just how Symfony wires everything up.