将数据库连接传递给phpunit test

时间:2015-08-17 10:38:24

标签: php phpunit

我正在尝试测试一个执行select语句的函数,但是我有点混淆了我应该将连接传递给这个函数的方式以及如何断言数据。 这是具有我想要测试的功能的类:

class AdProviders {
  public $providers = null;

  protected $db = null;

  function __construct() {

  }

  function getDbh() {
    if ($this->db === null){
      $this->db = Slim::getInstance()->db;
    }
    return $this->db->getConnection();
  }

  function setDbh($db) {
    $this->db = $db;
  }

  function getProviders() {
    if ($this->providers == null){
      $DBH = $this->getDbh();
      $query = "select * from providers";
      $STH = $DBH->query($query);
      $STH->setFetchMode(PDO::FETCH_ASSOC);
      while($provider = $STH->fetch()) {
        $this->providers[$provider['id']] = $provider;
      }
    }
    return $this->providers;
  }
}

这是我的测试:

require dirname(__FILE__).'/../../src/vendor/autoload.php';

class AdProvidersTest extends PHPUnit_Extensions_Database_TestCase
{
    /**
     * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection
     */
    public function getConnection()
    {
        $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'root', 'LWw6A$cXvvf');

        return $this->createDefaultDBConnection($pdo, 'testdb');

    }

    /**
     * @return PHPUnit_Extensions_Database_DataSet_IDataSet
     */
    public function getDataSet()
    {
        return $this->createXMLDataSet(dirname(__FILE__).'/../dbTest/fixtures/providers.xml');
    }

    public function testgetProviders_compareResult()
    {
        $db = $this->getConnection();
        $fixture = new AdProviders($db);
        $res = $fixture->getProviders();
    }
}

当我运行测试功能时,我收到以下错误:

1) AdProvidersTest::testgetProviders_compareResult
Trying to get property of non-object

为什么我得到它?以及如何获取providers.xml中的数据 使用getProviders? THX

1 个答案:

答案 0 :(得分:2)

您必须将AdProviders类的构造函数更改为可以将PDO实例传递给它。否则$fixture = new AdProviders($db);将无效。

请更改

function __construct() {

}

function __construct($db) {
   $this->db = $db;
}

更新:

我看到您没有在PDO媒体资源中存储AdProviders::$db个实例。如果您将PDO个实例传递给__construct,则还应该从

更改方法setDbh
  function getDbh() {
    if ($this->db === null){
      $this->db = Slim::getInstance()->db;
    }
    return $this->db->getConnection();
  }

  function getDbh() {
    if ($this->db === null){
      $this->db = Slim::getInstance()->db->getConnection();
    }
    return $this->db;
  }