【问题标题】:how to test the protected method in zend如何在zend中测试受保护的方法
【发布时间】:2011-08-21 22:12:27
【问题描述】:

我想在zend项目中测试一个模型,

<?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) {

        );
    }

}

application/model 文件夹下的模型,它扩展了一个基类 Custom_Model_Base,它与类 User 在同一文件夹下。

在我的测试中,我尝试以这种方式创建一个新的 User 对象

    <?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);
    }

}

这是 CustomModelBase.php: 抽象类 Custom_Model_Base { 受保护的函数 __construct($adapter=null) {} }

它给了我错误,说“PHP 致命错误:在第 4 行的 \application\models\User.php 中找不到类 'Custom_Model_Base'”,我在 User.php 中包含“CustomModelBase.php”,它给了我另一个错误“PHP 致命错误:从第 13 行的 D:\PHP\apache2\htdocs\ID24_Xiao\tests\application\models\UserTest.php 中的上下文 'Model_User2Test' 调用受保护的 Application_Model_User::__construct()”

那我该怎么办呢?谁能给点建议?

【问题讨论】:

  • 您的构造函数是否有理由受到保护?
  • 不是您问题的解决方案,但应该是 $this->user2 = new Application_Model_User();而不是 $this->user2 = new Application_Model_User2();

标签: unit-testing zend-framework phpunit


【解决方案1】:

如果您使用 5.3.2 或更好的版本,您可以这样做:

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());
}

【讨论】:

  • 其实被保护的方法就是构造函数,创建被测对象是不是也一样?
  • 在zend测试中没有定义ReflectionMethod()?
  • no,php5.2,如何在不影响phpunit安装等部分的情况下更新php版本?
  • $method 应该通过调用 invoke 来调用(可以将对象作为参数)。
【解决方案2】:

您不能从类外部调用任何受保护的类成员。
将访问修饰符从 protected 更改为 public
或者创建一个静态函数来提供该类的实例,例如

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

【讨论】:

    【解决方案3】:

    正如 Jeff 所说,您可以通过像这样公开构造函数来使其可测试:

     public function __construct() { ...
    

    【讨论】:

      猜你喜欢
      • 2012-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      • 2014-12-24
      • 2017-06-24
      • 1970-01-01
      相关资源
      最近更新 更多