Próbuję napisać unit test dla formularza z konstruktorem, który jako argument ma EntityManager.
Po wielu próbach i przeszukaniu całego internetu udało mi się utworzyć taki obiekt w teście, ale i tak otrzymuję taki błąd:
Error: Call to a member function getPrioritysInUserLocaleToForm() on null
Klasa testu:
<?php
namespace Tests\AppBundle\Form\Type;
use AppBundle\Form\TodoType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\PreloadedExtension;
use Symfony\Component\Form\Test\TypeTestCase;
class TodoTypeTest extends TypeTestCase
{
private $em;
protected function setUp()
{
$this->em = $this->createMock(EntityManagerInterface::class);
parent::setUp();
}
protected function getExtensions()
{
return array(
new PreloadedExtension([
new TodoType($this->em)
], [])
);
}
public function testTodoType()
{
$form = $this->factory->create(TodoType::class, ['locale' => 'en']);
}
}
i klasa formularza:
<?php
namespace AppBundle\Form;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type as Type;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class TodoType extends AbstractType
{
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', Type\TextType::class)
->add('content', Type\TextareaType::class)
->add('priority', Type\ChoiceType::class, [ 'choices' => $this->addChoicesInUserLocale($options['locale']) ])
->add('dueDate', Type\DateTimeType::class, [
'widget' => 'single_text',
'attr' => ['class' => 'js-datepicker'],
'html5' => false,
]);
}
public function configureOptions( OptionsResolver $resolver )
{
$resolver->setDefaults( [
'locale' => 'en',
] );
}
/**
* Method adds array with choices to ChoiceType in builder
*
* @param string $locale User's locale
*
* @return array All priority in user _locale formatted as array e.g. ['1' => 'low', ...]
*/
private function addChoicesInUserLocale(string $locale): array
{
return $this->em->getRepository('AppBundle:Priority')
->getPrioritysInUserLocaleToForm($locale);
}
}
Nie mogę znaleźć w ogóle podobnego błędu w google, ani na innych stronach, a sam sobie też nie mogę z tym poradzić. Z góry dzięki za wskazówki ;)