lundi 8 janvier 2018

Create multi entities in Symfony4 Unit tests

Since few days, I'm trying to learn Symfony Unit Test. I made my first test but I noticed one thing : For my first test, I tested a simple implode for some tags :

class TagsTransformerTest extends TestCase
{
    public function testTransform()
  {
      $tagsArray = [
        $this->createTag('Symfony'),
        $this->createTag('Test'),
        $this->createTag('Unit'),
      ];

      $transformer = $this->getMockedTransformer();
      $tagsTransformed = $transformer->transform($tagsArray);

      $this->assertEquals('Symfony, Test, Unit', $tagsTransformed);
  }

  private function getMockedTransformer()
  {
      $entityManager = $this
          ->getMockBuilder(ObjectManager::class)
          ->disableOriginalConstructor()
          ->getMock();

      return new TagsTransformer($entityManager);
  }

  private function createTag($name)
  {
     $tag = new Tag();
     $tag->setName($name);

     return $tag;
  }

}

As you can see, I have to create a createTag() method to build some tags, but I wonder if I can like Laravel :

$anakin = factory(User::class)->states('anakin')->create();
$post = factory(Post::class)->create(['author_id' => $anakin->id]);
factory(Post::class, 2)->create();
factory(Comment::class, 3)->create(['post_id' => $post->id]);

My question is, is there any way to use a object like factory in Symfony to avoid going through an alternative method ?

Aucun commentaire:

Enregistrer un commentaire