2015-01-13 24 views
1

我正在使用Symfony2和Doctrine 2.我試圖採用TDD方法。有人可以給我一個基本的例子的單元測試類的教義實體類嗎?如何爲Doctrine實體類編寫測試類?

衷心感謝您的幫助。

+2

我不認爲''Doctrine''單元測試一個很好的例子實體類很有意義,因爲實體類不應包含任何邏輯。 –

+1

這是真的。感謝您的建議。我想如果他們有自定義的邏輯/函數,測試版本庫將會更有意義。 – Sid

+0

他們沒有邏輯,但他們有結構。單元測試可以測試結構。 另外@marcoshoya給出了一個函數測試的例子,可以用來確保表結構在遷移中沒有改變。 –

回答

6

這是單元測試的一個實體的一個簡單的示例:

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()); 
    } 
} 
+0

這個測試類測試一個實體的自動生成方法!你真的需要測試嗎? – Ghasrfakhri

0

上有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(); 
    } 
} 
+4

這是一個存儲庫測試,而不是一個實體。 – Roman

相關問題