Steven Scott
Steven Scott

Reputation: 11250

PHPUnit with Dependency Injection, testing the mock object using instanceof()

I have decoupled/abstract code that uses Dependency Injection. However, with abstracted code, my database classes all return a PDO object, since I have different classes for working with different databases.

For instance:

class MySQL extends \Database
{
...
    public function CreateConnection
    {
        ...
        return $PDOConnection;
    }
}

class Oracle extends \Database
{
...
    public function CreateConnection
    {
        ...
        return $PDOConnection;
    }
}

The Database class then has common routines for manipulating queries, creating statements etc... This keeps the main code database unaware, since the internal methods of RunQuery, LimitResults, etc... may be called in the code, and will be translated to the proper code and format for each database.

My question now arises on how to test the object returned. While I know I am going to mock it for my test, I do want to ensure that I can check that the class is returning the proper object. I may want to return a cache object, or something else based on configuration, as PDO may not be used.

Therefore, I would like to check the Mock Object is of the right instance.

public testPDOObjectReturned()
{
    $MockObject = $this->getMock('\Database\MYSQL');
    $MockObject->expects($this->any())
               ->method('CreateConnection');
    $this->assertInstanceof('PDO', $MockObject->CreateConnection(MYSQL::UsePDO));
}

However, I do not know how to set the returned object to be a class/object for testing with InstanceOf().

I get an error:

1) lib\Database\PDO\MYSQL_Test::testCreateConnection
Failed asserting that null is an instance of class "PDO".

How can I set the class returned to test that it is the right object type?

Upvotes: 0

Views: 1078

Answers (1)

Bram Gerritsen
Bram Gerritsen

Reputation: 7238

Your CreateConnection stub should return something.

$MockObject->expects($this->any())
           ->method('CreateConnection');
           ->will($this->returnValue($this->getMock('PDO')));

Upvotes: 1

Related Questions