由于下面的模型,我在启动单元测试时出错
代码
$mockPDOStatement = $this->createMock(PDOStatement::class);错误
Error: Call to undefined method ReflectionUnionType::getName()PHP8.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;
    }
}发布于 2022-01-27 08:47:42
对我来说很管用
私有函数getConnectionMock() {
$mockPDOStatement = $this
   ->getMockBuilder("stdClass" /* or whatever has a fetchAll */)
   ->setMethods(array("fetchAll", "execute", "fetchColumn"))
   ->getMock();
$mockPDOStatement->method('fetchAll')
     ->willReturn($this->eventsData);
$mockPDOStatement->method('fetchColumn')
     ->willReturn(2);
$mockPDO = $this
   ->getMockBuilder("ThePDOObject")
   ->disableOriginalConstructor()
   ->setMethods(array("prepare", "lastInsertId"))
   ->getMock();
$mockPDO->method('prepare')
     ->willReturn($mockPDOStatement);
$mockPDO->method('lastInsertId')
     ->willReturn(1);
$mock = $this->createMock(EplanDBConnectionService::class);
$mock->method('getPdo')
     ->willReturn($mockPDO);
return $mock;}
https://stackoverflow.com/questions/70741906
复制相似问题