【问题标题】:Unable to unit test PHP CodeIgniter application with session enabled无法在启用会话的情况下对 PHP CodeIgniter 应用程序进行单元测试
【发布时间】:2016-04-12 16:47:23
【问题描述】:

我在 CodeIgniter 3 中开发了我的 PHP 应用程序,测试用例使用 PHPUnit 测试框架(而不是内置)编写。在我将会话加载到autoload.php: [$autoload['libraries'] = array('session')] 之前,我的测试用例运行良好。当我这样做并运行测试用例时,会抛出以下信息:

Unable to locate the specified class: Session.php

我什至创建了一个空白 CI 项目,其中的 Welcome 控制器只有一个添加功能。虽然我没有使用session,但是当我将它添加到autoload.php 时,就会出现错误。我尽可能多地使用谷歌搜索,但我找到的解决方案都没有解决我的问题。有没有人遇到过这个问题,有快速的解决方法吗?

CITest.php

class CITest extends PHPUnit_Framework_TestCase {
  private $CI;
  public function setUp() {
    $this->CI = &get_instance();
  }

  public function testAdd() {
    $this->wel = new Welcome;
    $this->assertEquals(15, $this->wel->sum(5, 10));
  }
}

Welcome.php

class Welcome extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->library('session');
    }

    public function index() {
        echo "index...";
    }

    public function sum($x, $y) {
        return $x + $y;
    }
}

【问题讨论】:

  • $this->load->library('session');控制器中添加这个
  • @Abdulla 我试过了,仍然抛出同样的错误。
  • 它看起来像目录配置错误您可以尝试在 index.php 文件中写入应用程序文件夹和其他文件夹的完整路径
  • 在会话库顶部设置ob_start()
  • 是因为 CodeIgniter 的实现。 CodeIgniter 不希望有多个控制器实例。

标签: php codeigniter unit-testing session phpunit


【解决方案1】:

我将Session.php 文件从System/library/Session 复制到System/library。测试运行没有任何问题。

【讨论】:

    【解决方案2】:

    对我有用的是添加如下的空构造函数

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

    完整的类是这样的

    class Welcome_test extends TestCase
    {
        public function __construct()
        {
            parent::__construct();
        }
    
        public function test_index()
        {
           //your tests here
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-30
      • 2016-03-11
      • 1970-01-01
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      • 2012-03-21
      相关资源
      最近更新 更多