gpt4 book ai didi

PHPUnit - 如何在 PHPUnit_Framework_TestCase 中实例化我的 pdo 类?

转载 作者:行者123 更新时间:2023-11-29 01:55:09 26 4
gpt4 key购买 nike

如何在 PHPUnit_Framework_TestCase 中实例化我的 pdo 类?

例如,这是我的\test\SuitTest.php

namespace Test;

use PHPUnit_Framework_TestCase;

class SuiteTest extends PHPUnit_Framework_TestCase
{
protected $PDO = null;

public function __construct()
{
parent::__construct();
$this->PDO = new \Foo\Adaptor\PdoAdaptor(); // the pdo is not instantiated at all - I think!
}

protected function truncateTables ($tables)
{
foreach ($tables as $table) {
$this->PDO->truncateTable($table);
}
}

/**
* DO NOT DELETE, REQUIRED TO AVOID FAILURE OF NO TESTS IN FILE
* PHPUnit is ignoring the exclude in the phpunit.xml config file
*/
public function testDummyTest()
{
}
}

我想使用我用于开发和生产的 pdo 类,它位于 \app\source\Adaptor\PdoAdaptor.php,

<?php

namespace Foo\Adaptor;

use PDO;

class PdoAdaptor
{
protected $PDO = null;
protected $dsn = 'mysql:host=localhost;dbname=phpunit', $username = 'root', $password = 'xxxx';

/*
* Make the pdo connection.
* @return object $PDO
*/
public function connect()
{
try {
$this->PDO = new PDO($this->dsn, $this->username, $this->password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$this->PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Unset props.
unset($this->dsn);
unset($this->username);
unset($this->password);
} catch (PDOException $error) {
// Call the getError function
$this->getError($error);
}
}

public function truncateTable($table)
{
$sql = "TRUNCATE TABLE $table";
$command = $this->PDO->prepare($sql);
$command->execute();
}
}

当我运行 phpunit 来测试我的代码时出现这个错误,

Fatal error: Call to a member function prepare() on null

SuiteTest 中的 construct 方法中根本没有实例化 pdo - 我认为!

这是我的目录结构,

enter image description here

最佳答案

使用 setUpBeforeClass方法(注意:它是静态的)

protected static $pdo;

public static function setUpBeforeClass()
{
static::$pdo = new PdoAdapter();
}

然后只需在测试中使用 static::$pdoself::$pdo 访问您的 pdo 实例。

关于PHPUnit - 如何在 PHPUnit_Framework_TestCase 中实例化我的 pdo 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31157610/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com