2

When mocking an object with PHPUnit, how do I access properties of the object which are normally accessed via overloading, i.e. via __get()?

For example, in the code below I am testing a Post object. Each Post has an author, which of type Role. Each Role has a Signature property.

$author = $this->getMockBuilder('App_Model_Domain_Role')
        ->disableOriginalConstructor()
        ->getMock();        

$author->expects($this->any())
        ->method('__get')
        ->will($this->returnValue('authorname'));

As you can see I mock the Role object, then configure it to return a string ('authorname') when __get() is called. The Post object which I am testing refers to $this->author->signature. I am expecting it to return 'authorname', but instead the test errors out saying that $signature is an undefined property.

I tried configuring the mock as above but without the method() call (thinking that the expects() and will() calls would then apply to all the mock's methods) but still no success.

Any ideas?

Also, if you know of a good tutorial on PHPUnit mocks I'd be keen to see it - the manual seems to assume prior testing knowledge in this particular area.

4

1 に答える 1

2

私はあなたと同じコードを試しました、そしてそれは私のために働いています。私のPHPUnitのバージョンは3.7.12です。どのバージョンを使用していますか?古いバージョンを実行している場合は、アップグレードしてみてください。

public function testMockingMagicGetter()
{
    $myMock = $this->getMockBuilder('MyClass')
        ->disableOriginalConstructor()
        ->getMock();
    $myMock
        ->expects($this->any())
        ->method('__get')
        ->will($this->returnValue('authorname'));
    var_dump($myMock->signature);
    var_dump($myMock->dummy);
    var_dump($myMock->someprop);
}

結果:

string(10) "authorname"
string(10) "authorname"
string(10) "authorname"
于 2013-02-19T20:22:18.480 に答える