0

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?

1 Answer 1

1

Your CreateConnection stub should return something.

$MockObject->expects($this->any())
           ->method('CreateConnection');
           ->will($this->returnValue($this->getMock('PDO')));
Sign up to request clarification or add additional context in comments.

1 Comment

It works, but why is it needed? Aren't we bypassing the method call completely? It looks like by doing this we're mocking the very same result we're supposed to be testing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.