简体   繁体   English

如何在 Symfony2 ORM 实体上对 getId() 方法进行单元测试?

[英]How to unit test getId() method on Symfony2 ORM entity?

I want to unit test all my Catalog Entity methods and have a problem with testing getter getId().我想对我所有的目录实体方法进行单元测试,并且在测试 getter getId() 时遇到问题。 When I create the Catalog (new Catalog()) there is no Id set and no setId() method!当我创建目录 (new Catalog()) 时,没有设置 Id 和 setId() 方法!

My first stupid step was to write the mok:我第一个愚蠢的步骤是写 mok:

public function testGetId()
{
    $category = $this->getMock('\Dimas\CatalogBundle\Entity\Category');
    $category->expects($this->any())
        ->method('getId')
        ->will($this->returnValue(352));
    $this->assertEquals(352, $category->getId());
}

But this dummy-test did not tested my entity!但是这个虚拟测试并没有测试我的实体!

What is the right way to test getId() method?测试 getId() 方法的正确方法是什么?

If you have generated IDs (by Doctrine, database auto-increment or something else), you'd be testing the Doctrine (etc.) code.如果您生成了 ID(通过 Doctrine、数据库自动增量或其他方式),您将测试 Doctrine(等)代码。

To test getId() properly, you'd have to set ID by yourself, either via constructor (prefered), or setter.要正确测试getId() ,您必须通过构造函数(首选)或 setter 自己设置 ID。

I personally prefer the second approach using UUID.我个人更喜欢使用 UUID 的第二种方法。 You can find more info with example here .您可以在此处通过示例找到更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM