0

I'm trying to mock a PDO object but am getting an error that reads "PDO::__construct() expects at least 1 parameter, 0 given"

The class that I am mocking is here:

class MockPDO extends PDO
{

public function __construct() {
try 
    {
     $dsn = "mysql:host=localhost;dbname=somedatabase";
     parent::__construct($dsn, "root", "root"); 
    }
    catch (PDOException $exception) 
    {
     die($exception->getMessage());
    }
 }
}

My test class is here

class DatabaseTest extends \PHPUnit_Framework_TestCase
{
public function testFindById() {
$pdo = $this->getMock('PDO', array('prepare'));
$stmt = $this->getMock('PDOStatement', array('execute', 'fetch'));
$stmt->expects($this->once())->method('execute')->with($this->equalTo(array(':id' => 2)));
$stmt->expects($this->once())->method('fetch');

$pdo->expects($this->once())->method('prepare')
  ->with($this->equalTo('SELECT * FROM sometable WHERE id => :id'))
  ->will($this->returnValue($stmt));
}

I know this is simple, but what am I doing wrong?

krisacorn
  • 831
  • 2
  • 13
  • 23
  • possible duplicate of [PDO \_\_constructs expects at least 1 parameter, 0 given](http://stackoverflow.com/questions/19904852/pdo-constructs-expects-at-least-1-parameter-0-given) – iam-decoder Sep 11 '14 at 20:43
  • The solution to http://stackoverflow.com/questions/19904852/pdo-constructs-expects-at-least-1-parameter-0-given cannot be applied here because I can only extend phpunit's test framework. – krisacorn Sep 11 '14 at 20:54

2 Answers2

2

My solution for this problem is to create a wrapper class for pdo. This is for destroying the constructor. Unless you provide valid connection string to the constructor

Example how to provide constructor arguments:

$pdo = $this->getMock('PDO', array('prepare', '__construct'), ["mysql:host=server;dbname=db;"]);

Solution:

class PDOMock extends \PDO {
    public function __construct() {} }

class PDOTest extends \PHPUnit_Framework_TestCase {
    public function setup() {
        $pdo = $this->getMockBuilder('PDOMock')
            ->getMock();
    } }
Lauri Orgla
  • 561
  • 3
  • 10
2

PhpUnit calls the constructor of the object, unless you explicitly tell not to

$pdo = $this->getMockBuilder('PDO')
    ->disableOriginalConstructor()
    ->setMethods(array('prepare'))
    ->getMock();
Maxim Krizhanovsky
  • 26,265
  • 5
  • 59
  • 89