PHPUnit - creating Mock objects to act as stubs for properties

家住魔仙堡 提交于 2019-12-18 12:53:17

问题


I'm trying to configure a Mock object in PHPunit to return values for different properties (that are accessed using the __get function)

Example:

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

I'm trying to mock this using:

$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"));

but this fails horribly :-(


回答1:


I haven't tried mocking __get yet, but maybe this will work:

// 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'));

I've already used $this->at() in a test and it works (but isn't an optimal solution). I got it from this tread:

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




回答2:


This should work:

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';
    }
}
... ... 


来源:https://stackoverflow.com/questions/3304633/phpunit-creating-mock-objects-to-act-as-stubs-for-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!