tags:

views:

519

answers:

1

I'm having problems when trying to mock objects with __get and __set methods (using simpletest).

Writing mock responses for __get doesn't smell right - the tests seem too tightly tied to implementation. Any recommendations for testing, or should I just avoid the magic methods completely ?

+2  A: 

I had the same problem and found the solution in the SimpleTest test cases:

From mock_objects_test.php:

class ClassWithSpecialMethods {
    function __get($name) { }
    function __set($name, $value) { }
    function __isset($name) { }
    function __unset($name) { }
    function __call($method, $arguments) { }
    function __toString() { }
}
Mock::generate('ClassWithSpecialMethods');

... snip ...

function testReturnFromSpecialAccessor() {
    $mock = new MockClassWithSpecialMethods();
    $mock->setReturnValue('__get', '1st Return', array('first'));
    $mock->setReturnValue('__get', '2nd Return', array('second'));
    $this->assertEqual($mock->first, '1st Return');
    $this->assertEqual($mock->second, '2nd Return');
}

function testcanExpectTheSettingOfValue() {
    $mock = new MockClassWithSpecialMethods();
    $mock->expectOnce('__set', array('a', 'A'));
    $mock->a = 'A';
}

A bit clunky, but it works. On the other hand, I think you're better off avoiding them... the large corporate system I'm working on uses them heavily and it's a nightmare to understand/visualise/debug/do anything with!