dsc80135 2018-01-08 09:50
浏览 65
已采纳

在Symfony4单元测试中创建多个实体

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 ?

  • 写回答

1条回答 默认 最新

  • douhuangjian9627 2018-01-08 09:58
    关注

    Better:

    $tagsTransformed = ($this->getMockedTransformer())->transform($tagsArray);
    $this->assertEquals('Symfony, Test, Unit', $tagsTransformed);
    

    Yes i think you can, check this

    $form = $this->factory->create(TestedType::class);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。
  • ¥15 各位 帮我看看如何写代码,打出来的图形要和如下图呈现的一样,急
  • ¥30 c#打开word开启修订并实时显示批注
  • ¥15 如何解决ldsc的这条报错/index error
  • ¥15 VS2022+WDK驱动开发环境
  • ¥30 关于#java#的问题,请各位专家解答!
  • ¥30 vue+element根据数据循环生成多个table,如何实现最后一列 平均分合并
  • ¥20 pcf8563时钟芯片不启振