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 ?

图片转代码服务由CSDN问答提供 功能建议

几天后,我正在尝试学习Symfony Unit Test。 我做了第一次测试,但我发现了一个 事情: 对于我的第一次测试,我测试了一些标签的简单内爆:

  class TagsTransformerTest扩展TestCase 
 {
公共函数testTransform()
 {
  $ tagsArray = [
 $ this-> createTag('Symfony'),
 $ this-> createTag('Test'),
 $ this-> createTag('Unit'),
];  
 
 $ transformer = $ this-> getMockedTransformer(); 
 $ tagsTransformed = $ transformer-> transform($ tagsArray); 
 
 $ this-> assertEquals('Symfony,Test,Unit'  ,$ tagsTransformed); 
} 
 
私有函数getMockedTransformer()
 {
 $ entityManager = $ this 
  - > getMockBuilder(ObjectManager :: class)
  - > disableOriginalConstructor()
  -  > getMock(); 
 
返回新的TagsTransformer($ entityManager); 
} 
 
私有函数createTag($ name)
 {
 $ tag = new Tag  (); 
 $ tag-> setName($ name); 
 
返回$ tag; 
} 
 
} 
   
 
 

As 你可以看到,我必须创建一个createTag()方法来构建一些标签,但我想知道我是否可以喜欢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]); 
   
 
 

我的问题是,有没有办法在Symfony中使用像工厂这样的对象来避免使用替代方法?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题