PHPUnit - 创建Mock对象以充当属性的存根

时间:2010-07-21 23:17:34

标签: php mocking phpunit

我正在尝试在PHPunit中配置Mock对象以返回不同属性的值(使用__get函数访问)

示例:

class OriginalObject {
 public function __get($name){
switch($name)
 case "ParameterA":
  return "ValueA";
 case "ParameterB":
  return "ValueB";
 }
}

我试图用以下方法来嘲笑:

$mockObject = $this->getMock("OrigionalObject");

$mockObject    ->expects($this->once())
    ->method('__get')
    ->with($this->equalTo('ParameterA'))
    ->will($this->returnValue("ValueA"));

$mockObject    ->expects($this->once())
    ->method('__get')
    ->with($this->equalTo('ParameterB'))
    ->will($this->returnValue("ValueB"));

但这很可怕: - (

2 个答案:

答案 0 :(得分:9)

我还没有尝试过嘲笑__get,但也许这会起作用:

// getMock() is deprecated
// $mockObject = $this->getMock("OrigionalObject");
$mockObject = $this->createMock("OrigionalObject");

$mockObject->expects($this->at(0))
    ->method('__get')
    ->with($this->equalTo('ParameterA'))
    ->will($this->returnValue('ValueA'));

$mockObject->expects($this->at(1))
    ->method('__get')
    ->with($this->equalTo('ParameterB'))
    ->will($this->returnValue('ValueB'));

我已经在测试中使用了$ this-> at()并且它可以工作(但不是最佳解决方案)。我从这个方面得到了它:

How can I get PHPUnit MockObjects to return different values based on a parameter?

答案 1 :(得分:4)

这应该有效:

class Test extends \PHPUnit_Framework_TestCase {
...
    function testSomething() {
         $mockObject = $this->getMock("OrigionalObject");

         $mockObject
              ->expects( $this->any() )
              ->method('__get')
              ->will( $this->returnCallback('myMockGetter'));
         ...
     }
...
}

function myMockGetter( $classPropertyName ) {
    switch( $classPropertyName ) {
        case 'ParameterA':
            return 'ValueA';

        case 'ParameterB':
            return 'ValueB';
    }
}
... ...