我正在尝试为返回深层实体结构的单元测试创建实体管理器的模拟。
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 :(得分:1)
看看Phake:http://phake.readthedocs.org/en/latest/index.html
你可以像方法Stubbing一样:
$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);