我有一个抽象类:
abstract class Base {
/**
* @var \PDO
*/
protected $_dbh;
protected $_logFile;
public function __construct($dbh, $logFile) {
$this->_dbh = $dbh;
$this->_logFile = $logFile;
}
}
.............
class bbb extends Base {
public function smth() {
$this->_addTracToDB([....]);
}
private function _addTracToDB($data) {
$sql = "INSERT INTO table1 (t_time, t_priority)
VALUES(:t_time, :t_priority)";
$query = $this->_dbh->prepare($sql);
$query->execute([
':t_time' => $data['timestamp'],
':t_priority' => $data['priority'],
]);
}
public function smth2() {
$sql = 'selct * from table2';
$query = $this->_dbh->query($sql);
return $query->fetchAll();
}
}
Tan我尝试用以下方法测试它:
class mockPDO extends \PDO
{
public function __construct ()
{}
}
class ChinaBaseTest extends DbTestAbstract {
protected $pdo;
protected function setUp() {
$this->pdo = $this->getMock('mockPDO', array('query'), array('sqlite:memory')); // *<-- error here*
// $this->pdo->expects($this->any())
// ->method('query')
// ->will($this->returnValue(new \PDOStatement()));
$this->pdo->expects($this->any())
->method('prepare')
->will($this->returnValue(new \PDOStatement()));
// $foo->query('SELECT * FROM users;'); // instantiated PDOStatement class will be returned
// var_dump($foo->getAvailableDrivers()); // take note that methods originally declared in PDO class is available too
$tableNames = array('guestbook');
$dataSet = $this->getConnection()->createDataSet($tableNames);
}
protected function getDataSet() {
return $this->createFlatXmlDataSet(__DIR__ . '/_data/myFlatXmlFixture.xml');
}
protected function _getDataFile($fileName) {
return file_get_contents(__DIR__ . '/_data/' . $fileName);
}
public function testParseSingle() {
$bbb = new bbb ($this->pdo, LOG_DIR . 'common.log');
$result = $bbb->smth($this->_getDataFile('787.log'));
$this->assertEquals(1, count($result));
$this->assertArrayHasKey(0, $result);
$result = $result[0];
$this->assertEquals(mktime(11, 39, 24, 9, 10, 2014), $result['timestamp']);
......
}
}
但是接受错误:
ReflectionException : Class Mock_mockPDO_b630d3bd does not have a constructor, so you cannot pass any constructor arguments
D:\........\myTest.php:26
这一行:$ this-&gt; pdo = $ this-&gt; getMock(&#39; mockPDO&#39;,
那可能是我错了路?
答案 0 :(得分:0)
你的构造函数不带参数:
class mockPDO extends \PDO
{
public function __construct ($arg)
{}
}
$this->pdo = $this->getMock('mockPDO', //the class name to mock
array('query'), //the methods to mock
array('sqlite:memory'));//arguments to pass to constructor