0

I don't know if the title clarifies what I want to do and if that way is efficient. But, I want to know if it is the best practice - Phpunit with Database.

I use Aura\Sql to manage connection with MySql database. Well, in my PHPUnit test class I created an initial mock method, see the example:

// Here a class construct.
$pdoMock = m::mock('Aura\Sql\ExtendedPdo');
$pdoMock->shouldReceive('fetchPairs')->andReturn([
'foo' => 'bar'
]);

$this->pdoConnection = m::mock('Aura\Sql\ConnectionLocator');
$this->pdoConnection->shouldReceive('getDefault')->andReturn($pdoMock);

Next an example of the a method PHPUunit that receive the test. The class LoadUsers call the method default of the Aura\SQl with name "getDefault" declared above.

$gateway = new LoadUsers($this->pdoConnection);
$gateway->readPairs(); // Returned array ['foo' => 'bar']

It is easy to see that at no time did I make a real connection to the database. Maybe, an alternative way is to make a real connectionn with the database and ignore the mock.

My big question is whether it is recommended to test a method that invokes a database connection in this way.

I will like to listen(read) opinions. Thanks

  • Unit tests should not connect to a database. That should be left to integration testing. Read [this](https://softwareengineering.stackexchange.com/questions/206539/unit-tests-and-databases-at-which-point-do-i-actually-connect-to-the-database). – El_Vanja Apr 02 '20 at 22:48
  • Yes, it can be a consideration. – Bernardo Castro Apr 03 '20 at 16:11

0 Answers0