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

Tim*_*Tim 17 php phpunit mocking

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

例:

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

我正在尝试使用以下方法来模拟:

$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"));
Run Code Online (Sandbox Code Playgroud)

但这很可怕:-(

koe*_*oen 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'));
Run Code Online (Sandbox Code Playgroud)

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

如何让PHPUnit MockObjects根据参数返回不同的值?