2014-09-03 42 views
2

我試圖爲返回深層實體結構的單元測試創​​建實體管理器的模擬。將Doctrine實體轉換爲單元測試的模擬

Basicaly我想要改造這個:

$p1 = new Product(); 
    $p1->setName("product 1"); 
    // ... 

    $c = new Command(); 
    $c->setDate(new Date()); 
    $c->setId(1); 
    $c->addProduct($p1); 
    // ... 

進入這個:

p1 = $this->getMock('\Acme\DemoBundle\Entity\Product'); 
    $p1->expects($this->any()) 
     ->method('getName') 
     ->will($this->returnValue("product 1")); 
    // ... 

    $c = $this->getMock('\Acme\DemoBundle\Entity\Command'); 
    $c->expects($this->any()) 
     ->method('getDate') 
     ->will($this->returnValue(new Date())); 
    $c->expects($this->any()) 
     ->method('getId') 
     ->will($this->returnValue(1)); 
    $c->expects($this->any()) 
     ->method('getProducts') 
     ->will($this->returnValue(array($p1))); 
    // ... 

有一個簡單的和不那麼冗長的方式來得到這個?

感謝

+0

你可以用嘲諷是簡單一點 – 2014-09-03 05:54:21

+0

也許你應該看看[BazingaFakerBundle]( https://github.com/willdurand/BazingaFakerBundle),一個基於[Faker](https://github.com/fzaninotto/Faker)的Symfony2軟件包。 – mneute 2014-09-03 12:31:56

回答

1

Thake看看Phake:http://phake.readthedocs.org/en/latest/index.html

您可以法成株像:

$this->item1 = Phake::mock('Item'); 
    $this->item2 = Phake::mock('Item'); 
    $this->item3 = Phake::mock('Item'); 

    Phake::when($this->item1)->getPrice()->thenReturn(100); 
    Phake::when($this->item2)->getPrice()->thenReturn(200); 
    Phake::when($this->item3)->getPrice()->thenReturn(300); 

    $this->shoppingCart = new ShoppingCart(); 
    $this->shoppingCart->addItem($this->item1); 
    $this->shoppingCart->addItem($this->item2); 
    $this->shoppingCart->addItem($this->item3);