如何为Doctrine实体类编写测试类?

时间:2015-01-13 11:33:11

标签: symfony model doctrine-orm tdd entity

我正在使用Symfony2和Doctrine 2.我正在尝试采用TDD方法。有人可以给我一个Doctrine实体类的单元测试类的基本示例吗?

真诚地感谢任何帮助。

2 个答案:

答案 0 :(得分:8)

这是一个实体单元测试的简单示例:

class MessageTest extends \PHPUnit_Framework_TestCase {

    /**
     * @var Message
     */
    protected $object;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        $this->object = new Message();
    }

    public function testGetterAndSetter() {

        $this->assertNull($this->object->getId());

        $date = new \DateTime();

        $this->object->setDate($date);
        $this->assertEquals($date, $this->object->getDate());

        $this->object->setMessage("message");
        $this->assertEquals("message", $this->object->getMessage());

        $this->object->setSuccess(true);
        $this->assertTrue($this->object->getSuccess());
    }
}

答案 1 :(得分:-2)

http://symfony.com/doc/current/cookbook/testing/doctrine.html

上有一个很好的例子
// src/Acme/StoreBundle/Tests/Entity/ProductRepositoryFunctionalTest.php
namespace Acme\StoreBundle\Tests\Entity;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

class ProductRepositoryFunctionalTest extends KernelTestCase
{
    /**
     * @var \Doctrine\ORM\EntityManager
     */
    private $em;

    /**
     * {@inheritDoc}
     */
    public function setUp()
    {
        self::bootKernel();
        $this->em = static::$kernel->getContainer()
            ->get('doctrine')
            ->getManager()
        ;
    }

    public function testSearchByCategoryName()
    {
        $products = $this->em
            ->getRepository('AcmeStoreBundle:Product')
            ->searchByCategoryName('foo')
        ;

        $this->assertCount(1, $products);
    }

    /**
     * {@inheritDoc}
     */
    protected function tearDown()
    {
        parent::tearDown();
        $this->em->close();
    }
}