【发布时间】:2022-01-17 13:10:06
【问题描述】:
由于以下模型,我在启动单元测试时遇到错误
代码
$mockPDOStatement = $this->createMock(PDOStatement::class);
错误
Error: Call to undefined method ReflectionUnionType::getName()
PHP 8.1.1 PHPUnit 8.5.22
完整示例:
class Connection
{
public function getPdo()
{
return new PDO(
dbServer,
dbUsername,
dbPassword
);
}
}
class Events
{
private $connection;
public function __construct(Connection $connection)
{
$this->connection = $connection;
}
public function getEvent($id)
{
$query = 'SELECT * FROM events WHERE id=:id';
$pdo = $this->dbConnection->getPdo()->prepare($query);
$pdo->execute(["id" => $id]);
return $pdo->fetchAll(PDO::FETCH_ASSOC);
}
}
use PHPUnit\Framework\TestCase;
class EventsTest extends TestCase
{
private $eventData = [
'id' => '1',
'Description' => '',
'EndTime' => '2021-12-09 18:00:00',
'IsAllDayEvent' => '0',
'StartTime' => '2021-12-09 17:00:00',
'Subject' => 'Prueba Creada desde Google',
];
protected function setUp(): void
{
$this->eventd = new Events(
$this->getConnectionMock(),
);
}
public function testFetchMany()
{
$events = $this->eplanEventRepository->getEvent(1);
$this->assertIsArray($events);
}
private function getConnectionMock()
{
$mockPDOStatement = $this->createMock(PDOStatement::class);
$mockPDOStatement->method('fetchAll')
->willReturn($this->eventData);
$mockPDO = $this->createMock(PDO::class);
$mockPDO->method('prepare')
->willReturn($mockPDOStatement);
$mock = $this->createMock(Connection::class);
$mock->method('getPdo')
->willReturn($mockPDO);
return $mock;
}
}
【问题讨论】:
-
首先,你用的是什么框架(好像是Laravel)?其次,你为什么要嘲笑它?看起来这个类是一个核心类,所以你不要模拟核心类......更多地解释你想要实现的模拟。
-
感谢您的回复,我已经用一个我想做的例子更新了我的问题。
标签: php unit-testing mocking phpunit