Reputation: 744
I'm trying to create a mock of the entity manager for unit tests that returns a deep entity structure.
Basicaly I want to transform this :
$p1 = new Product();
$p1->setName("product 1");
// ...
$c = new Command();
$c->setDate(new Date());
$c->setId(1);
$c->addProduct($p1);
// ...
Into this :
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)));
// ...
Is there a simple and not so verbose way to get this ?
Thanks
Upvotes: 2
Views: 358
Reputation: 39460
Thake a look at Phake: http://phake.readthedocs.org/en/latest/index.html
You can Method Stubbing like:
$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);
Upvotes: 1