PHPUnit模拟对象和方法类型提示

Mic*_*ing 40 php phpunit unit-testing mocking

我正在尝试使用PHPunit创建\ SplObserver的模拟对象,并将模拟对象附加到\ SplSubject.当我尝试将模拟对象附加到实现\ SplSubject的类时,我得到一个可捕获的致命错误,说明模拟对象没有实现\ SplObserver:

PHP Catchable fatal error:  Argument 1 passed to ..\AbstractSubject::attach() must implement interface SplObserver, instance of PHPUnit_Framework_MockObject_Builder_InvocationMocker given, called in ../Decorator/ResultCacheTest.php on line 44 and defined in /users/.../AbstractSubject.php on line 49
Run Code Online (Sandbox Code Playgroud)

或多或少,这是代码:

// Edit: Using the fully qualified name doesn't work either
$observer = $this->getMock('SplObserver', array('update'))
    ->expects($this->once())
    ->method('update');

// Attach the mock object to the cache object and listen for the results to be set on cache
$this->_cache->attach($observer);

doSomethingThatSetsCache();
Run Code Online (Sandbox Code Playgroud)

我不确定它是否有所作为,但我使用的是PHP 5.3和PHPUnit 3.4.9

Ion*_*tan 74

更新

哦,实际上,问题很简单,但不知何故很难发现.代替:

$observer = $this->getMock('SplObserver', array('update'))
                 ->expects($this->once())
                 ->method('update');
Run Code Online (Sandbox Code Playgroud)

你必须写:

$observer = $this->getMock('SplObserver', array('update'));
$observer->expects($this->once())
         ->method('update');
Run Code Online (Sandbox Code Playgroud)

那是因为getMock()返回不同的东西method(),这就是你得到错误的原因.你传递了错误的对象attach.

原始答案

我认为你必须完全限定模拟的类型:

$observer = $this->getMock('\SplObserver', array('update'));
Run Code Online (Sandbox Code Playgroud)

  • 是! 就是这样 - 我试图通过流畅的界面变得过于聪明.谢谢你的帮助! (3认同)