views:

122

answers:

2

hi all

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 :-( Help please T

A: 

The same problem here. Does anybody knows how to mock class' properties?

myltik
A: 

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

$mockObject = $this->getMock("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:

http://stackoverflow.com/questions/277914/how-can-i-get-phpunit-mockobjects-to-return-differernt-values-based-on-a-paramete

koen
hey koen$this->at() works for me - Thank you ;-)Why don't you think that this is an optimal solution?
Tim
It's not really scalable and the test is difficult to read. A callback may be easier to read if you give it a good name. But in the first place I would look at trying to refactor the __get.
koen
also, you are testing state (which some regard as bad practice) and even more, private state (which many regard as a bad practice). Of course there are smart folks who don't see a problem in that and you may be one of them.
koen