【问题标题】:Convert Doctrine entity into a mock for unit test将 Doctrine 实体转换为模拟单元测试
【发布时间】:2014-10-27 10:34:35
【问题描述】:

我正在尝试为返回深层实体结构的单元测试创​​建实体管理器的模拟。

基本上我想改变这个:

  $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)));
  // ...

有没有一种简单而不那么冗长的方法来得到这个?

谢谢

【问题讨论】:

  • 可以用嘲讽的方式简单一点
  • 也许你应该看看BazingaFakerBundle,一个基于Faker的Symfony2包。

标签: unit-testing symfony doctrine-orm mocking entitymanager


【解决方案1】:

看看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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-18
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多