如何从Stub访问对象的属性?

时间:2015-11-27 09:32:13

标签: php phpunit codeception

我有简单的课程:

class MyClass {

    private $myProperty;

    public __construct($propertyValue) {
        $this->myProperty= $propertyValue;
    }

    public function myMethod() {
        // Something
    }

}

使用MyClass分类:

class MySecondClass {

    private $myClass;

    public __construct($myClassInst) {
        $this->myClass = $myClassInst;
    }

    public function doIt() {
        $this->myClass->myMethod();
    }

}

我对某些MySecondClass类进行了单元测试:

use Codeception\TestCase\Test;
use Codeception\Util\Stub;

class MySecondClassTest extends Test

    public function testDoIt() {
        $data = null;

        $myClass = Stub::construct('MyClass', ['propertyValue'], [
            'myMethod' => function() use (&$data) {
                // I want do that, but I can not!
                //$data = $this->myProperty;
            }

        $mySecondClass = new MySecondClass($myClass);
        $mySecondClass->doIt();

        $this->assertEquals($data, 'assertValue');
    ]);

}

如果要取消注释以上示例中的行:

PHP Warning:  Uncaught PHPUnit_Framework_Exception: Undefined variable: myProperty ...

如果myProperty是公开的:

PHPUnit_Framework_Exception: Undefined property: MySecondClassTest::$myProperty

问题:如果myProperty引用MySecondClassTest类的对象,如何从Stub访问MyClass的属性$this

1 个答案:

答案 0 :(得分:1)

YAGNI。您正在MySecondClass::doIt中测试逻辑,而不是MyClass

您模拟MyClass,并使用常量值定义来自MyClass::myMethod的确切响应。基本上,您的testDoIt()读取:假设我们有MyClass的实例返回一些确切的值,我们希望MySecondClass::doIt返回一些确切的值。而已。与MyClass::myProperty毫无关系。

修改 回答评论

  

对于公共属性,它也是错误的,因为$ this引用了MySecondClassTest对象:PHPUnit_Framework_Exception:未定义属性:MySecondClassTest :: $ myProperty

首先,我认为你误解了测试双打的概念。 Stub不是模拟类的实例。这是一个存根。它模仿 模拟类的行为,并且只在定义的部分中。

其次,闭包中的$this始终引用定义闭包的类。在您的情况下,它是MySecondClassTest

同样,问题不在于属性的可见性,而是在测试中需要此属性的值。你不。它违反了单元测试的核心原则。