Symfony - test custom listener on postPersist

Viewed 91

I am trying to Mock my custom listener behaviour in Symfony project so I can run tests where I want to check if the persisring of data goes well.

I am very new at writing tests so definitly need some input on this.

class MyCustomListener
{
    const CREATED = 'created';

    private $entityService;
    private $em;

    public function __construct(MyEntityService $entityService, EntityManagerInterface $em)
    {
        $this->entityService = $entityService;
        $this->em = $em;
    }

    public function postPersist(LifecycleEventArgs $args)
    {
        $this->handle($args, self::CREATED);
    }

    public function handle($args, $action)
    {
        $entityManager = $args->getEntityManager();
        $uow = $entityManager->getUnitOfWork();
        $entity = $args->getObject();
        $changes = $uow->getEntityChangeSet($entity);

        if ($entity instanceof MyEntity) {
              $new = new MyEntity();
              $new->setEntityId($entity);
              $new->setTypeOfAction($action);

              $this->em->persist($new);
              $this->em->flush();
          }
      }
  }

And I tried to mock this listener like:

public function testListener()
{
    $myEntityService = $this->createMock(MyEntityService::class);
    $lifecycleArgs = $this->createMock(LifecycleEventArgs::class);

    $entityManagerInterface = $this->createMock(EntityManagerInterface::class);
    $entityManagerInterface->method('getEntityManager');
    $uow = $entityManagerInterface->method('getUnitOfWork');
    $entity = $lifecycleArgs->method('getObject');
    $changes = $uow->method('getEntityChangeSet')->with((array)$this->equalTo($entity));

    $eventListener = new MyCustomListener($myEntityService);
    $eventListener->postPersist($lifecycleArgs);

    $output = $eventListener->handle($eventListener, 'created');
    self::assertNull($output);
}

With an error:

Trying to configure method "getEntityManager" which cannot be configured because it does not exist, has not been specified, is final, or is static

Am I on the right track as on the end I want to have desired output of checking if MyEntity object is persisted correctly.

0 Answers
Related