PHPUnit模拟多个期望

时间:2012-04-17 02:52:14

标签: mocking phpunit

来自谷歌模拟的背景,我很惊讶这不起作用,除非我做错了。

我只想确保使用特定类类型调用永远方法,但可以为其他类类型调用。所以这里有我解释我想要的代码:

$this->entityManagerMock
      ->expects($this->any())
      ->method('persist');
$this->entityManagerMock
     ->expects($this->never())
     ->method('persist')
     ->with($this->isInstanceOf('MySpecificClass'));

现在我收到类似的消息:

Doctrine\ORM\EntityManager::persist(DifferentClassType Object (...)) was not expected to be called.

当我期望第一次期望处理它时。

我试过了,但结果是一样的:

$this->entityManagerMock
      ->expects($this->any())
      ->method('persist')
      ->with($this->anything());
$this->entityManagerMock
     ->expects($this->never())
     ->method('persist')
     ->with($this->isInstanceOf('MySpecificClass'));

这是我第一次在PHPUnit中使用模拟,但在我看来with已被破坏和/或没用。我知道现在大多数Web开发人员都使用TDD,所以必须有更好的方法来实现这一点。

1 个答案:

答案 0 :(得分:2)

作为解决方法,您可以使用returnCallback

$this->entityManagerMock
     ->expects($this->any())
     ->method('persist')
     ->will($this->returnCallback(function ($object) {
         self::assertNotInstanceOf('MySpecificClass', $object);
     }));
相关问题