开发者

how to test the protected method in zend

开发者 https://www.devze.com 2023-03-04 05:46 出处:网络
I want to test a model in zend project, <?php //require_once(\'CustomModelBase.php\'); class Application_Model_User extends Custom_Model_Base {

I want to test a model in zend project,

<?php

//require_once('CustomModelBase.php');

class Application_Model_User extends Custom_Model_Base {


    protected function __construct() {
        parent::__construct();
    }

    static function create(array $data) {

    }

    static function load($id) {

    }

    static function find($name, $order=null, $limit=null, $offset=null) {

        );
    }

}

the model in under application/model folder, it extends a base class Custom_Model_Base which is under the same folder as class User.

In my test, I try to create a new object of User in this way

    <?php


class Model_UserTest extends ControllerTestCase

{
    protected $user2;

    public function setUp() {

        parent::setUp();

        $this->user2 = new Application_Model_User2();
    }

    public function testCanDoTest() {
        $this->assertTrue(true);
    }

}

this is CustomModelBase.php: abstract class Custom_Model_Base { protected function __construct($adapter=null) {} }

it gives me error, say "PHP Fatal error: Class 'Custom_Model_Base' not found in \application\models\User.php on line 4", the I include "CustomModelBase.php" in User.php,it gives me another error "PHP Fatal error: Call to protected Application_Model_User::__construct() from context 'Model_User2Test' in D:\PHP\apache2\htdocs\ID24_Xiao\tests\ap开发者_如何学Cplication\models \UserTest.php on line 13"

then How could I handle it? can anyone give some suggestion?


If you use 5.3.2 or better you could do it this way:

public function testCanDoTest() {

    // set method "nameOfProctedMethod" to accessible on Class App...
    $method = new ReflectionMethod(
        'Application_Model_User2', 'nameOfProtectedMethod'
    );

    $method->setAccessible(true);
    $this->assertTrue($method->doSomething());
}


You can not call any protected member of class from outside the class.
Either change the access modifier from protected to public
Or create a static function which will give the instance of that class, for e.g.

static function getInstance(){
    return new Model_UserTest();
}


As Jeff has said, you can make your constructor testable by making it public like this:

 public function __construct() { ...
0

精彩评论

暂无评论...
验证码 换一张
取 消